214 Commits
Author SHA1 Message Date
Saul Moro cd3a914112 fix(env): keep the user scope's env block when a project pulls (#878)
* fix(env): make doctor and uninstall act on their own scope's env block (#876)

A shell profile can carry a user-scope block and a project-scope block, but
doctor, uninstall and the active-profile resolver only ever read the first
`# [teamai:env:start]` pair. Doctor in a project then blamed the #661
backslash for the user scope's block, uninstall's plan missed a second block
of its own, and its cleanup step removed the first block whatever scope it
belonged to.

Add findEnvBlocks/findEnvBlockFor, which pick a block by the env.sh it
sources (the ownership test uninstall already used), and use them in all
three consumers. With only another scope's block present, doctor now says the
profile carries no block for this env.sh. The ownership test also accepts the
all-backslash spelling of the path, so a #661 block of this scope keeps its
diagnosis. The marker format and how pull writes the profile are unchanged.

* fix(env): keep the user scope's env block when a project pulls (#876)

Each pull replaced the first `# [teamai:env:start]` block in the shell
profile, whichever scope it belonged to, so a member with a user and a
project scope got only the last-pulled scope's env in new shells.

Injection now picks the block by the env.sh it sources. A scope replaces
its own block. Otherwise a project takes over another project's block,
never the user scope's (recognised by the env.sh the user-scope config
resolves to), and a user scope goes in right before the project block. The
user block therefore precedes the project block, so a project value wins on
a shared key, and the project block stays last-wins. Other blocks are left
alone; the marker format and the skip-when-unchanged write are unchanged.

* fix(env): address #876 review findings on env block ownership

- Drop the all-backslash spelling from candidateSpellings; the #661
  doctor tests now use a Windows-form data home instead.
- envBlockReferencesDataHome requires a path boundary before a raw
  spelling, so /home/me/.teamai/env.sh no longer claims a block that
  sources /data/home/me/.teamai/env.sh.
- resolveActiveShellProfile falls back to the first file along the
  sourcing chain that holds any teamai block when none holds this
  scope's, so a first user pull or a second project pull on the Git
  Bash chain lands next to the existing block instead of after the
  .bashrc source line.
- injectShellProfile uses one "user scope's block" predicate for both
  scopes; a block that sources no env.sh (pre-env.sh inline exports)
  is the user scope's, so a project pull no longer takes it over.
- Tests build well-formed blocks with EnvHandler.generateShellBlock.

Refs #876

* fix(env): match an env.sh path only up to its end (#876)

* fix(env): keep the user block when the user config does not parse (#876)
2026-09-29 11:09:05 +08:00
Saul Moro facc6104f6 fix: keep self-update off npm link checkouts, and report hook injection only on change (#871) (#874)
* fix(update): leave an npm link checkout alone instead of replacing it with the registry package

When the running CLI is not under node_modules (an npm link checkout),
resolveInstallPrefix returns null and doUpdate ran a prefix-less
npm install -g. That lands in npm's default global prefix, where npm link
put its symlink, so the next hook run swapped the checkout for the
published package. Skip the install and say how to update instead.

* fix(hooks): report OMP, OpenCode and Pi hook injection only when the file changes

These injectors rewrote their file and logged success on every pull, so
an up-to-date pull listed them as injected while Claude and Codex, which
already compare before writing, printed nothing. Use writeIfChanged and
log at debug level when the file is current.

* fix(update): refuse an unsupported install before prompting, and keep the skip in debug.log

Review follow-ups: resolve the install target before the prompt policy so
nobody confirms an update that is then skipped; persist the skip warning
because hooks discard stderr; word it for every null target, not only a
link; tell the user to pull before rebuilding; pass --registry in the
suggested install command.

* fix(hooks): report Hermes and OpenClaw hook injection only when something changes

Both are reached by the pull reconcile and still logged success on every
run. OpenClaw now writes its two files with writeIfChanged; Hermes also
reports whether its config.yaml entry and allowlist were written.

* fix(update): persist the vendored-install skip to debug.log too

Adversarial review follow-up: the Stop hook discards stderr, so the
vendored-layout refusal left no trace while the linked-checkout refusal
next to it is persisted.
2026-09-29 11:06:54 +08:00
ydflow 479f811b52 fix(recall): normalize scores across knowledge sources (#891) 2026-09-29 09:50:12 +08:00
Saul Moro 11657bcfab fix(recall): read each agent's session variable so recall quality joins its session (#887) 2026-09-29 09:49:01 +08:00
Saul Moro f836db4230 fix(push): publish the env files env add leaves in a standalone clone (#881) (#885) 2026-09-29 09:48:00 +08:00
Saul Moro 488c3074cf fix(learnings): publish what an older import --from-mr left in the checkout (#823) (#838)
* fix(learnings): publish what an older import --from-mr left in the checkout (#823)

Item 7. import --from-mr in 0.25.0 to 0.26.0-beta.3 wrote
learnings/<date>-<title>.md, with source_mr in its frontmatter, into the
learnings checkout and never committed it. Nothing published it. In single-repo mode it also kept
`git worktree remove` from removing the checkout an older teamai left in
.teamai/, so every pull and contribute stopped on CheckoutRefusedError.
publishQueuedLearnings now takes the sync lock first, and under it, before
listing the queue, queues every untracked file of exactly that shape
(directly under learnings/, date name, source_mr), in the active namespace
and with contribute's name, then deletes the original. It finds the one
checkout this repo registers for the branch (git worktree list), so the
shared checkout and the old .teamai/learnings-wt are both covered and
another repository's never is. A file the branch or the queue already has,
by source_mr or by content, is deleted instead, and the warning names what
has it. A dry run touches nothing.

Item 21. The branch side of that duplicate check was the checkout's own
tracked files. In single-repo mode the checkout is often the old
.teamai/learnings-wt, which nothing syncs any more, so a teammate's later
import of the same MR was missed and the remnant went out as a duplicate.
When there are remnants, the check now also fetches origin/teamai-learnings
(best effort) and reads what origin has that the checkout's commit lacks.

Item 20. pull --dry-run published the queue: publishQueuedLearnings
honoured dryRun only for the remnants. It now stops after listing the queue,
and pull prints "[dry-run] Would publish N queued learning(s)" instead of
publishing or warning.

Maintenance sweep. publishLearningsMaintenance staged all of learnings/,
so a confidence write-back or a prune swept any uncommitted file into its
commit. confidence write-back, prune and promote now return the files they
wrote or removed, and only those are staged (a removed file git never
tracked is left out, since naming it would fail the add). That exposed a
second bug:
simple-git lists a staged rename under `renamed`, not `staged`, so a
`prune --archive` with nothing else to stage counted as nothing to commit
and was never published. commitAndPushAt now counts renames.

#814 follow-ups. drainCheckoutQueue is gone: the preAction migration moves a
checkout's queue before contribute and import --from-mr. Retire-only now
says "Retired <legacy> to <backup>: this project's data already lives in
<partition>"; a linked worktree lands there too, so "Finished an
interrupted migration" was wrong for it. config.yaml.*.tmp, the temp an
interrupted config save leaves (#831), is ignored in the single-repo and
project-scope .gitignore, and the single-repo self-heal adds it.

Item 15. After a failed refresh, readableReportsWorktree called ensure
without the reports lock, so it could create the checkout while a writer
that had just taken the lock created it too. It now refreshes once more
under the lock and throws the cause if that fails as well.

Item 17. init replaced the team clone before saving the new config, so an
init that stopped in between (an unknown --role, a busy queue lock) left
the old team's config.yaml beside the new team's clone. Just before it
clones another owner's repo, init now settles the old install as the final
save would (queue set aside, indexes dropped) and moves its config.yaml to
config.yaml.previous. A failed init then leaves no config, and commands ask
for teamai init.

* fix(learnings): address review — literal pathspecs, carry settings after a failed clone

Maintenance now stages exactly the files it names: commitAndPushAt and the
removed-file ls-files lookup pass --literal-pathspecs, so a learning named
with [ or * no longer stages the stray files it matches as a pattern.

init reads the config it set aside when the rerun finds none, so an init
whose replacement clone failed no longer drops enabledAgents,
disabledAgents, toolRoots and inheritUserScope on the next run.

* fix(learnings): address review — HTTP maintenance, agent lists on a plain rerun

An HTTP install's learnings dir is no git checkout, so the removed-file
ls-files lookup threw after a prune had already deleted the file. It now
returns the same non-fatal failed publish commitAndPush gives.

init without --agent keeps the carried enabledAgents and disabledAgents,
so a rerun after a failed replacement clone no longer reactivates tools
uninstall --agent excluded.

* fix(learnings): address review — retry maintenance a busy lock or failed push kept local, keep remnants while origin is unreachable

* fix(learnings): address review — queue remnants when origin has no learnings branch, never let one bad maintenance record or remnant block the rest

* fix(learnings): address review — dedup remnants against origin's tree, keep a maintenance record a read failed on

* fix(learnings): address review — commit only the published paths, not the whole index (#823)

* fix(learnings): address review — keep a staged file across the push-retry rebase (#823)

The path-limited commit leaves a file someone else staged in the checkout,
and git refuses to rebase with anything staged, so a non-fast-forward push
failed every retry. Snapshot it with git stash create around the rebase, as
syncWorktree does, and re-apply it with --index so it stays staged.

* fix(learnings): address review — read the queue for remnant dedup under the queue lock and ownership check; move a stale config aside when init reuses a clone (#823)

* ci: re-run checks (flaky dry-run-load-path test, unrelated to this PR)

* fix(learnings): address review — keep staged files staged when the snapshot restore conflicts; never publish a hand edit as a recorded maintenance run (#823)

* fix(learnings): address review — resolve snapshot conflicts from the snapshot without a reset, keep a conflicting staged file unstaged, no hand-edit warning for a merged maintenance commit (#823)

* fix(learnings): address review — point the unpublished-edit warning at git status (#823)
2026-09-28 10:43:32 +08:00
Ruifeng Xue 47438926fa fix: prevent stale Copilot rules from reverting team updates (#857)
* fix: prevent stale Copilot rules from reverting team updates

* fix: skip excluded agents during rule pre-push sync
2026-09-28 10:42:07 +08:00
ydflowandydflow d319816c6b fix(agents): carry the agent's model into the Cursor render (#830) (#856)
renderForCursor was the one renderer that dropped spec.model: Claude, the
Codex family and Copilot all write the agent's model into their native
file, and reverseFromCursor reads it back (COMMON_CURSOR_FIELDS whitelists
it), so a team agent with a concrete model ran on Cursor's default model
silently. #830's design notes name the gap ('Cursor drops model when it
renders agents today') and ask for it as a separate change — this is that
change: write the value verbatim, as the other renderers do. The
model[effort=...] form stays with the alias proposal.

Co-authored-by: ydflow <ydflow@users.noreply.github.com>
2026-09-27 20:58:12 +08:00
Saul Moro 46ffa96f2c feat(init): let a member choose the git provider with --provider (#789) (#844)
* feat(init): let a member choose the git provider with --provider (#789)

A member of a team on self-hosted GitLab had to configure GITLAB_TOKEN
even when they only sync and never need the CLI to open merge requests.
`teamai init <repo> --provider <name>` now uses the named provider
instead of detecting one, and records it in the member's local config.
PR/MR creation and doctor's provider checks prefer it over the team's
teamai.yaml, which stays unchanged, so other members keep detection.
With `git`, push pushes the branch and says the MR must be opened by
hand, as it already does for a provider: git team repo.

* fix(init): address review — guard --provider gitlab and keep --provider git out of teamai.yaml

--provider gitlab on a host with no configured GitLab instance would send
the token to gitlab.com (the API base defaults there); stop with a hint to
set GITLAB_URL or use --provider git. A teamai.yaml that init creates now
records the provider detected from the URL instead of a member's git
override, matching the docs.

* fix(init): address review — do not record git as the team provider on an unconfigured GitLab

With --provider git, a teamai.yaml that init creates (empty team repo or
first self-mode init) recorded detectProvider(url), which skips the
self-hosted GitLab probe. On an unconfigured instance that wrote
`provider: git` and cost every teammate automatic merge requests. Init now
resolves the team provider as it would without the flag, including the
probe, and stops with a GITLAB_URL hint when the probe finds GitLab.

* fix(gitlab): address review — refuse a TEAMAI_GITLAB_HOST that disagrees with GITLAB_URL

Repos on TEAMAI_GITLAB_HOST were detected as GitLab while the API base,
token included, came from GITLAB_URL. Stop before any request when the
two name different hosts, and let gitlabWhoami surface the configuration
error instead of reporting a failed login.
2026-09-26 21:43:22 +08:00
Smilewithoutfalling ba04f18205 feat(code-knowledge): add Swift support to the AST and heuristic tracks (#842)
Registers tree-sitter-swift (already shipped inside the pinned
tree-sitter-wasms@0.1.13) with the captures walk.ts needs for types,
protocols, functions, imports, calls and conformance relations, and adds a
regex extractor so Swift facts still surface when the AST path is
unavailable. .swift is now collected, mapped to the swift language and
marked by the key-file patterns.

Swift imports are module-level, so they must not reach the tsconfig `paths`
mapping, which is TypeScript-only: doing so made `import Shared` resolve to
an unrelated .ts file and suppressed the EXTERNAL_IMPORT gap that records
the truth. Swift specifiers are reported as gaps instead, the way Go's
`import "fmt"` already is.

No new dependency; package.json is untouched.

Closes #712
2026-09-26 21:10:57 +08:00
Saul Moro 49675a9787 fix(push): stop reverting a teammate's update from HOME or a stale .teamai copy (#823) (#835)
* fix(push): stop reverting a teammate's update from HOME or a stale .teamai copy (#823)

Item 4, user scope: push compared HOME's rules and skills with the shared
lastPullRev only, because the per-checkout push bases of #819 were keyed for
project scope alone. After a push synced HOME's unedited copy to a teammate's
R2, the next push compared it with R1 and offered it back over the teammate's
R3. A user-scope pull now records HOME under checkoutKey(HOME) in the user
state.json, and push reads and extends it like a project checkout's. The
user-scope fast path still reads the shared fields, and an install with no
record yet keeps comparing with lastPullRev without the unrecorded-checkout
refusal: HOME is the scope's only checkout, so that revision is its own.

Item 19, inherited user scope: a project pull with inheritUserScope rewrites
HOME's skills, rules and agents under lastInheritedPullRev without moving the
user scope's push bases, so the next user-scope push offered a teammate's
newer update back the same way. That pull now adds its revision to HOME's
pushBaseRevs, creating the record from lastPullRev if there is none, and
leaves the record's rev, lastPullRev and the fast paths alone.

Item 10, single-repo: the active tree's .teamai/rules and .teamai/skills are
push sources, and on a branch behind the default branch they hold older team
versions nobody edited, which push listed as modified. The isPastVersionOf
guard that held only placed rules now covers every .teamai/rules copy, and
.teamai/skills gets the same guard: a skill is skipped with a warning when
every team file whose copy differs is an older version of it. A team file
missing locally is a teammate's addition when the member's branch never added
it, and the member's deletion otherwise; member-only files are ignored, as the
equality check already ignores them.

The checkout-base resolution that push and the agents scan each repeated
(key, record, checkoutBaseRevs, lastPullRev fallback) is now one exported
helper, resolveCheckoutBases, next to checkoutBaseRevs in pull.ts; pull uses
the same key for its record.

* fix(push): address review — record HOME's push base in an upgraded install (#823)

An upgraded user-scope install with no HOME record synced HOME from R1 to R2
on its first push but saved no base, because push recorded one only when the
bases came from a record. A teammate's R3 then made the next push compare the
R2 copy with lastPullRev R1 and offer it back. Push now creates HOME's record
from lastPullRev (userScopeRecord, shared with the inherited pull) and adds
the revision its sync reached. An unrecorded project checkout still records
nothing, since its fallback base may be another checkout's.

skill-data: contribute-member explains the stale .teamai copy warning and
how to publish an edit of such a copy.

* fix(push): address review — keep HOME's inherited base and a partial pull's delivered base (#823)

* fix(push): keep the push bases of skills a pull held, and match a replaced root rule at every base (#823)
2026-09-26 19:24:28 +08:00
Saul Moro 81aa8ea63e fix(learnings): find learnings despite a broken manifest and in the dashboard; show the MR import prompt (#823) (#834)
* fix(learnings): find learnings despite a broken manifest and in the dashboard; show the MR import prompt (#823)

Three places that decide which learnings are found, and the MR import
prompt.

Recall index rebuild (item 12). When recall had to build a missing index,
one unreadable roles.yaml or projects.yaml failed the whole build:
deliveredIndexSources and resolveActiveLearningsNamespaces threw, the error
went to log.debug, and recall said "No learnings available. Run `teamai
pull` first", which pull does not fix. Each now runs in its own try.
Learnings do not depend on the manifests and are always indexed: a broken
projects.yaml leaves only the shared root, never every namespace. Docs,
rules and skills get empty lists (undefined would index the whole trees),
and one warning names the cause; a broken projects.yaml, which both read,
gives one warning for both. The partial index is saved like any
other, so later recalls stay quiet and the next pull rebuilds it whole. A
skills collision with no index to keep skills from indexed none silently;
IndexedSkills' keep-indexed now carries the conflict line and recall shows
it when there are no indexed skills to keep (no index, or an older one).
Any other build failure is shown with its cause, not as "No learnings
available".

import --from-mr duplicate check (item 9). The scan listed only each root's
top level, so learnings under learnings/<ns>/, where #825 files MR
learnings, were never compared. Its result fed only a "marking as
superseded" warning, and nothing stored or read LearningDraft.supersedes,
so the claim was false. The scan (now findOverlappingLearnings) also walks
the active project namespaces, as the index does (safe single segments,
first root wins per relative path), and the warning becomes a
possible-duplicate notice naming the files. `import` ran the extraction as a task,
with the logger silenced, so importFromMR's warning never reached the
terminal; the extraction now runs before the tasks (item 18), where the
logger prints it. The namespaces are resolved first: a broken projects.yaml narrows the check to the
shared root with a warning, as recall does, so --dry-run and --output keep
working. LearningDraft.supersedes and SUPERSEDE_THRESHOLD are removed. The
CI extractor still reads only the root (it has no LocalConfig).

Dashboard knowledge report (item 16). Its fallback index, built when no
search index exists, passed no learningsNamespaces, so project learnings
were missing in both scopes; in user scope it read learningsRoots().read,
which keeps another repository's learnings checkout in the write root
(#808). It now uses indexableLearningsRoots in user scope, as project scope
already did, and resolves the active namespaces with the paths. A broken
projects.yaml leaves the shared root, with a warning when the report builds
its own index.

import --from-mr prompt (item 18). importFromMR, which asks "Accept
learning? [Y/n]" on a readline, ran inside the first listr2 task. In a
terminal the default renderer holds stdout back while a task runs, so only a
spinner showed and the prompt appeared after it was answered. The
extraction now runs before the task list, which starts at "Publish
learning" with the extraction's result as its context.

* fix(learnings): address review — write the partial recall index past the shrink guard (#823)

With a manifest recall cannot read, the rebuild leaves docs, rules and
skills out on purpose. Against an older-format index of a full corpus the
result is under 20% of it, so buildIndex's shrink guard kept the old file
and recall searched the entries its warning said were left out. The
degraded rebuild now passes `partial`, which skips the guard; every other
build keeps it.

* fix(learnings): address review — skip the older recall index when the partial one cannot be written (#823)

* fix(learnings): address review — show queued learnings in the dashboard's fallback index (#823)

The dashboard's temporary index now reads the contribution queue, as recall's
does; promotion and prune candidates keep to the published roots. The recall
rule tells the agent to relay the skipped-older-index warning.
2026-09-26 19:23:46 +08:00
Saul Moro b136c9c654 fix(pull): do not deliver an env, hook or MCP entry with a mistyped key (#822) (#833)
* fix(pull): do not deliver an env, hook or MCP entry with a mistyped key (#822)

Item 1. Env, hook and MCP entry schemas are plain z.object, which strips
unknown keys, so a mistyped scoping key (`role:` for `roles:`) vanished and
the entry reached every member. Each reader now reports the keys an entry
was written with that its schema does not know (known keys come from the
schema's own shape), and keepScopedEntry does not deliver such an entry and
warns once, naming the file, the entry and the key, the same path the
removed `projects:` key takes. doctor's per-entry-key check is retitled to
cover it. `env add`/`env remove` and `remove mcp` keep such a key when they
rewrite the file; `remove mcp` edits the YAML document instead of
re-serializing the parsed servers.

Item 4. recall ended every result with a Chinese line; it is English now.

Item 2 is not a bug: tags reaching a tagged skill in an inactive namespace
is the behavior #337 added and roles-tags-pull tests. The design doc's
Known gaps entry now says so.

Item 3 (pull --dry-run warnings) is left to #832.

* fix(env): warn when env add updates a variable pull does not deliver (#822)

Updating a variable that carries an unknown key keeps the key, so the
variable stays undelivered; env add now says so instead of only reporting
'Updated env variable'.

* fix(pull): keep installed MCP servers and hooks when their file has no known top-level key (#822)

A hooks or MCP file with `server:` for `servers:` parsed as empty and
removed every installed team server or hook for every member, silently.
Such a file now fails like one that does not parse, naming the keys found
and the key expected. An extra key beside a known one is still ignored.
2026-09-26 19:17:22 +08:00
Saul Moro 7c834ce428 fix(data-layout): let every self-mode worktree publish learnings and keep its queue (#808) (#814) 2026-09-26 00:29:00 +08:00
Saul Moro e79db174c4 fix(push): stop offering a teammate's update back as a local edit (#823) (#827)
Three more ways push could list a copy the member never edited as modified,
ready to send a teammate's change back as the old version.

Single-repo mode (item 2). Push runs against a knowledge worktree whose team
root is <wt>/.teamai, a subdirectory of the git repo. The pre-push sync read
each base version with `git show <rev>:rules/x.md`, which git resolves from
the repo root, so it never found one, and every rule or skill a teammate
updated read as a local edit. The three reads now pass `./<path>`, which git
resolves from the working directory, as getFileContentWhenAdded and the agent
guard already did.

Placed agents (item 3). An agent placed with --role/--project is held when it
changed on the team since this machine's copy was current, and "current"
meant the version at the shared lastPullRev, which a pull in another checkout
moves past a copy a stale worktree still holds (the #812 revert, for agents).
The guard now reads this checkout's bases through checkoutBaseRevs, and falls
back to the shared lastPullRev for a checkout with no entry, as the pre-push
sync does. Push bases record where the sync moved rules and skills, not
agents, so the copy stays at the revision pull delivered: the guard holds an
agent that differs from its version at any base. Push records the team HEAD
as a base before the scan, and the file there is always the current one, so
the version the agent was added with is compared too whenever a base
predates it; otherwise a placement that landed after the last pull would go
back over a teammate's later edit. The hold message now says "this checkout".

Skill copy (item 5). The sync overwrote a local skill in place, so a copy
that failed partway left files from two revisions, matching no base, and the
next push listed the skill as modified. The update is now built in a hidden
sibling (the local copy, then the team version over it, so files only the
member has survive as before) and renamed into place; a failure leaves the
previous version whole. The stage carries the local modes, so cleanup makes
a read-only stage writable before removing it, and warns with the path if a
leftover cannot be removed; if the previous version cannot be renamed back,
the error names where it is.

Item 4 (user-scope push base) follows once #814 is merged.
2026-09-25 20:15:59 +08:00
Saul Moro 21cb76aa49 feat: one namespace model for every resource type (#707) (#816)
* chore: start one namespace model for every resource type (#707)

* refactor(pull): check agent and skill namespace collisions with one resolver (#707)

Add src/namespace-resolver.ts, the pure rule tickets 02-05 build on: an
active namespace item replaces the root item of the same name, and a name
twice in one place or in two active namespaces is a tagged conflict naming
both sources. The result depends only on the active order, not read order.

Agents and skills now run their duplicate checks through it and throw the
same messages. Agents still treat root + namespace as an error.

Add fast-check for the resolver's property tests.

* feat(env,hooks,mcp): scope env, hooks and MCP servers by namespace (#707)

env/<ns>/env.yaml, hooks/<ns>/hooks.yaml and mcp/<ns>/mcp.yaml are read where
<ns> is active in resources.env/hooks/mcp; a namespace entry replaces the root
entry of the same key, hook id or server name. A broken active file, a name
twice in one file or in two active namespaces stops that type for the run and
keeps what is installed. Per-entry projects: (and roles: on env) reach nobody;
roles: on hooks and MCP keeps filtering with a deprecation warning. Unknown
resources: keys warn instead of failing the manifest.

* feat(pull): let an active namespace item replace the root item for skills, agents, rules and claudemd (#707)

With a role or project configured, an item in an active namespace now
replaces the root item of the same name, whole:

- agents by stem: root + namespace is no longer a duplicate error, and a
  recorded (placed) agent replaces the root agent too
- skills by name, including a root skill received through a tag; an
  install removes the files of the version it replaces
- rules by first-level file name, in tool dirs and Hermes' SOUL.md block
- claudemd files by name in the managed block

Two active namespaces with one rule or claudemd name stop that type for
the run and keep what is installed. Push writes an edited overridden
skill, agent or rule back to its namespace, and the skills push scan
covers role and project namespaces. The placement record is withdrawn
by a same-name shared-root file only in legacy mode. Recall indexes the
skills pull delivers. doctor lists overrides, and in legacy mode repeated
names, as notes. Legacy mode is otherwise unchanged.

* fix(pull): deliver both namespace rules and claudemd files of one name (#707)

Rules and claudemd have no namespace-vs-namespace conflict: each
namespace rule keeps its own local path and each claudemd file its own
place in the block, so two active namespaces with one first-level name
are both delivered, as before. Only root suppression applies.

doctor override and legacy repeated-name notes now use the same wording
as the env, hooks and MCP ones. The usage guide and admin reference say
to keep overridable shared content at the root, with an example.

* fix(pull): stop only skills or agents on a namespace collision (#707)

Two active namespaces with one skill name or agent stem used to throw
and abort the whole scope, so rules, env, docs, cleanup and the search
index were skipped too. resolveDesiredSkills, resolveDesiredAgents,
scanRoleAwareSkills and filterAgentsByNamespaces now return a tagged
conflict. pull warns, leaves that type as installed (no install, no
inactive-namespace sweep) and syncs the rest. doctor reports the
collision as before; recall indexes no skills while it stands.

* feat(env,hooks,mcp): namespace flags, origins in status and doctor, docs (#707)

env add/remove take --role/--project; remove mcp searches every file and asks
for --role/--project when several define the name; push picks up
env/<ns>/env.yaml. status, list and doctor show where each entry comes from;
doctor lists overrides as notes and per-entry roles:/projects: as one
informational check. Usage guides and the admin skill reference describe the
namespace files; the #668 e2e moves onto them.

* test(env): show a broken env file stops env only (#707)

* fix(remove): remove an MCP server from the root file by default (#707)

remove mcp <name> follows push's convention: mcp/mcp.yaml when it defines the
name, else the one namespace file that does; --role/--project pick a namespace.
Only a name several namespace files (and not the root) define is refused.

* test(remove): expect namespace files in sorted order (#707)

* feat(docs): deliver a declared docs namespace only where it is active (#707)

A docs/<ns>/ that any role or project lists under resources.docs now
reaches only members with that namespace active; an undeclared
docs/<dir>/ stays shared. Leaving a namespace removes its local docs that
are byte-equal to the team copy and keeps edited ones with a line.
team-codebase is rejected as a docs namespace. The search index (pull,
recall, contribute) and doctor's "Team docs delivered" use the same set.

* feat(models): scope team model profiles by namespace and bind keys to their gateway (#707)

models/<ns>/models.yaml, declared under resources.models, replaces the root
profile with the same id while <ns> is active. A team API key is stored per
profile id and base_url origin, so pull never writes a key next to a gateway
on another origin; it prints the models switch line instead. Conflicts and
broken files stop model updates for the run. models list and doctor show
where each profile comes from; push validates every models file.

* docs(models): describe model profiles by namespace and key binding (#707)

* docs: list docs among the axes declared by hand (#707)

* docs: describe one namespace model for every resource type (#707)

Rewrite the multi-project design doc's precedence section for
namespace-over-root, add the per-type conflict, failure and legacy-mode
rules, and replace the per-entry key rows in the product overview. The
JSON doctor notes now also carry namespace notes.

* docs(changelog): replace per-entry scoping with namespace files (#707)

Drop the beta-only per-entry projects: entry, add the namespace axes,
the override, the per-type failure policy, the roles: deprecation on
hooks and MCP, and the upgrade-every-member-first note.

* docs(changelog): say the model key binding re-keys once and affects only betas (#707)

* refactor(namespaces): one warn-once registry instead of the quiet flag (#707)

Namespace fallback warnings, entry notices and unknown resources: keys
now go through utils/warn-once, reset once per pull, so the quiet option
threaded through eleven signatures is gone. The one-line wrappers
resolveTeamEnv, resolveTeamMcpServers and resolveTeamProfiles are removed;
every caller uses resolveEntries/resolveEntriesFor with the type's reader.

* refactor(namespaces): shared entry-file helpers, no unsafe casts in new code (#707)

- listEntryFiles/entryFileAbsolutePath replace the per-type file listers
  in env, mcp and models and the repeated path joins.
- gatewaySuffix replaces three spellings of the gateway suffix.
- LATER_RESOURCE_TYPES and friends are named for what they are:
  HAND_DECLARED_RESOURCE_TYPES, HandDeclaredNamespacesShape.
- Error messages use instanceof Error; manifest role/project ids are
  narrowed instead of cast; mapResources builds a typed object; pull
  writes env through an EnvHandler instance instead of a cast.
- status keys counts by entry type; rules localNameFor reuses
  deliversEveryNamespace, whose false answer is now documented.

* refactor(desired): move the desired-set resolvers out of pull.ts (#707)

Commands must stay thin, and recall, contribute and doctor imported
pull.js only to learn what a member receives. The skills, agents, rules
and claudemd resolvers, RolePullContext and the index sources now live in
src/resources/desired.ts; root suppression, the override note and the
repeated-name grouping live in namespace-resolver.

- A skill or agent conflict is a tagged DeliveryConflict carrying the
  resolver's NamespaceConflict, rendered once by describeDeliveryConflict
  (wording unchanged); DesiredItems names the result union.
- DesiredItems keeps each override, so doctor no longer rebuilds skill
  and agent overrides by hand.
- recall and contribute share deliveredIndexSources; pull indexes through
  the same indexedSkills instead of a second copy.
- doctor: one unresolvableCheck for skills, agents and docs; the docs
  check reports an unreadable manifest instead of returning nothing; the
  namespace notes catch only the team-repo reads.
- docs withdrawal reuses utils pruneEmptyDirs.

* fix(pull): name both files in a skill or agent conflict (#707)

Story 8 asks for a message naming both files. A skill or agent conflict
named only the namespaces, and an agent defined twice inside one
namespace (agents/a/x.md next to agents/a/x.yaml) read as 'found in
active namespaces "a" and "a"'. The duplicate case now names its one
place, and both cases list the two files.

* fix(rules): only a delivered namespace rule replaces the root rule, in every tool (#707)

- The rules override ran before the tag filter, so a namespace rule the
  member's tag subscription excludes still suppressed the root rule and
  the member received neither. The tag filter now runs first.
- JoyCode, OMP, Pi and Copilot share their rule directory with the
  member's own rules, so the stale sweep deletes nothing there unless a
  tombstone names it: the root rule a namespace rule replaced stayed
  installed and both versions loaded (story 6). pullAllRules now removes
  such a copy while it is byte-equal to its render, as agents do.

* fix(recall): keep the indexed skills while a skills conflict holds them (#707)

On a skills conflict pull keeps the installed skills, but the index was
rebuilt with none, so recall returned none of the skills the member still
has. The index now keeps the skills entries it already held, and pull
does the same when resolving the skills fails.

* fix(hooks,mcp): fail hooks inject and mcp inject when team entries do not resolve (#707)

reconcileTeamHooksForConfig returned [] when the team hooks could not be
resolved, the same value as a team without hooks, so hooks inject printed
'Hooks injected into all AI tool settings' and exited 0 over a broken
hooks/<ns>/hooks.yaml. It now returns { ok: false }, and hooks inject
exits 1 after the warning that names the file. mcp inject said 'Already
up to date.' in the same case; the MCP reconcile now marks the result
unresolved and mcp inject exits 1.

* fix(models): bind a beta API key to the gateway it was sent to, once (#707)

- A key a 0.26.0 beta stored under team:<id> counted for whatever origin
  the root profile had now, so a root profile moved to another host got
  the old key written next to it. The first pull or models command that
  reads such a key now binds it to the origin TeamAI last wrote into the
  agents switched to that profile (the root's current origin when it is
  among them), else to the root's current origin, and never re-reads the
  unbound key. Pull then leaves a moved agent alone and asks for the
  switch.
- The 'switch to set a key' and 'no longer active' lines are written to
  debug.log too: SessionStart pulls run silent.
- Legacy mode, which reads no namespace, says a profile 'was removed'.
- A models command whose profiles do not resolve reports it with
  log.error and exit code 1, as env list and mcp list do, instead of
  throwing.

* fix(entries): keep 0.25 files that repeat a name under different roles: working (#707)

0.25.0 let hooks.yaml and mcp.yaml repeat a hook or server name under
different roles:, delivering every copy that passed the role filter (MCP
kept the last). The namespace resolver treated that as a duplicate, so a
member holding both roles, or a role-less member in a team with
projects.yaml, stopped receiving hooks or MCP entirely. During the
roles: deprecation window such a repeat is delivered as in 0.25; a name
repeated without roles: on every copy is still a duplicate.

Also restores the test that the role filter runs before
requireTeamScripts, so the transparency print lists only what will run.

* feat(doctor): say where each entry type's entries come from (#707)

The spec asks doctor, like status and the list commands, to show each
entry's namespace; doctor listed overrides only. For env, hooks, MCP and
models, a namespace contributing any entry now adds a note counting the
entries by origin, 'env: 3 received here (2 root, 1 checkout)', from the
describeOrigins that status uses.

* test(pull): env and hooks conflicts between two namespaces, and builtin: in a namespace file (#707)

Seam 1 asks every type to show, through pull, that two active namespaces
defining one name keep the installed state and name both files. Env and
hooks were covered only through doctor and the handler; so was the
warning for builtin: in a namespace hooks file.

* docs(skill-data): hooks and MCP edits are published with git, not teamai push (#707)

manage-admin.md told admins to publish hooks/MCP file edits with
teamai push, which sweeps only rules/, env/ and .codebuddy-plugin/, so
an agent following it would push nothing. It now says to commit and
push the file with git, as the usage guide does.

* refactor(models): read switched agents without a cast (#707)

* docs(changelog): doctor counts entries per namespace; inject fails on unresolved entries (#707)

* refactor(pull): drop imports the resolver move left unused (#707)

* fix(hooks): install the built-in hooks when the team hooks do not resolve (#707)

A first init or bootstrap whose team hooks did not resolve (a broken
namespace file, a clash, a duplicate id) installed no built-in hook, so
the session-start pull that heals the member never ran. Installed team
hooks are still kept; the built-in hooks are now installed where missing,
with the root file's builtin: overrides whenever hooks/hooks.yaml parses,
and with their defaults only in a tool with no teamai hook when it does
not. init and bootstrap say that the team hooks were not installed.

* fix(manifest): keep an unknown resources: key when roles and projects save (#707)

zod stripped the key this CLI only warns about, so a projects or roles
command run on this version deleted a newer CLI's type from the team
repo for everyone.

* fix(docs): withdraw a copy the team edited after delivery, not only an unchanged one (#707)

Withdrawing an inactive docs namespace compared the local copy with the
current team file only. A doc the team changed after the member received
it was then kept forever with a false 'you edited it' line. A copy equal
to an earlier team commit is what the mirror delivered, so it goes too.

* fix(rules): withdraw a replaced root rule edited in the same push, name a kept copy (#707)

In the JoyCode, OMP, Pi and Copilot rule dirs, a replaced root rule's
copy was removed only while it matched the current root rule. When the
admin edited the root rule and added its namespace override in one push,
the member's unedited copy stayed loaded beside the override, silently.
It is now also compared with the render at the last pull, and a copy
that is kept is named with the fix.

* fix(doctor): fail a check when team hooks or model profiles do not resolve (#707)

teamai status counts such a type as 0 and says to run doctor, but doctor
had failing checks only for env and MCP, so a duplicate hook id or a
two-namespace clash showed nothing there.

* fix(env): warn when --role names a namespace nothing declares (#707)

env add/remove --role <ns> wrote env/<ns>/env.yaml for a namespace no
role or project lists under resources.env, so the variable reached
nobody and nothing said so. The same applies to remove mcp --role.

* fix(env): find a changed namespace env file whose name is not ASCII on push (#707)

git ls-files quotes such a path by default, so it never matched the name
on disk and push skipped the change.

* fix(entries): an active env, hooks, MCP or models file that cannot be read stops the type (#707)

The readers folded every read error into 'file does not exist', so an
unreadable namespace file silently delivered the root entry in place of
its override. Only ENOENT is absence now; any other error is a broken
file, like one that does not parse.

* fix(entries): match env, hooks, MCP and models namespace dirs case-folded, as docs does (#707)

A declared namespace was joined onto the path as written, so with
env: [checkout] and a directory env/Checkout/, macOS and Windows members
got the override and Linux members the root value.

* fix(doctor): split the legacy claudemd paths on '/', not path.sep (#707)

listFilesRecursive always joins with '/', so on Windows every path was
one segment and a claudemd/<ns>/x.md beside claudemd/x.md was never
reported.

* fix(recall): index the rules pull delivers, not the whole rules/ tree (#707)

A namespace rule replaces the root rule of its name, but recall, contribute
and pull indexed every file under rules/: the replaced root rule and the rules
of inactive namespaces came back from recall. Index the resolved rule set, as
docs and skills already do.

* fix(entries): write a namespace file into the directory pull reads it from (#707)

Pull matches a declared namespace to its directory case-folded, but --role and
--project returned the spelling typed. On a case-sensitive filesystem
`env add --project checkout` created env/checkout/, which shadowed
env/Checkout/ and dropped its variables from delivery.

* fix(remove): remove no MCP server by a bare name while an MCP file does not parse (#707)

The team scan skips a file that does not parse. With mcp/mcp.yaml broken,
`remove mcp db` took the one readable checkout/db as the target and removed
it. Refuse and name the file unless the readable root defines the name.

* docs: rules in recall, namespace writes and remove mcp on a broken file (#707)

* fix(remove): say the MCP file --role or --project names does not parse, not that the name is missing (#707)

The team scan skips a file that does not parse, so `remove mcp db --project
checkout` with a broken mcp/checkout/mcp.yaml reported "Not found". Name the
file and remove nothing.

* fix(skills): remove a leftover of another skill version only when it matches that version (#707)

Install removed any installed file at a path another team version of the skill
has, by path alone. A file a member added under that name, e.g. README.md
beside a namespace they never had, was deleted on every pull. Remove it only
when it is byte for byte that version's file; keep any other and name it.

* fix(env): edit no env file that does not parse, and no --project target after a failed refresh (#707)

env add and env remove read the target through parseEnvYaml, which answers an
empty list for a file that does not parse, then wrote that back: every
variable the file had was replaced. They now refuse and name the file.

--project resolves through manifest/projects.yaml. After a failed pull that
copy may be stale and name a namespace the project no longer uses, whose file
push would publish, so --project now changes nothing then. The root file and
--role do not depend on the manifest and still only warn.

* fix(pull): let no unusable namespace item replace the root one (#707)

A skill directory without SKILL.md replaced the root skill of its name:
install overlaid it and removed the installed SKILL.md as the other version's
leftover, while pull still counted the skill as synced. Such a directory is
no longer a skill; pull names it and keeps delivering the root one.

An agent file that does not parse delivers nothing, yet it still replaced the
root agent, and cleanup removed the unchanged root copy because no active
destination held that stem. The root agent now stays while its replacement
cannot be read or parsed.

* fix(push): take no namespace directory without SKILL.md for a member's skill (#707)

Pull stopped delivering such a directory in 6c7df8e3, but the push scan still
mapped the skill name to it. An unedited root skill then showed as modified,
and push wrote it into skills/<ns>/<name>/, deleting what was there and making
it a namespace skill that replaces the root one.

Also keep only a replaced root agent while its replacement does not parse, so
an unchanged copy from an inactive namespace is still removed, and put
renderedForTool's doc comment back on it.
2026-09-25 17:59:19 +08:00
Saul Moro f558b94614 fix(push): keep a teammate's update when pushing from a stale worktree (#812) (#819)
Before scanning, push syncs each rule and skill the member never edited to
the team repo's version, and "never edited" meant equal to the version at the
project's shared lastPullRev. state.json is shared by every worktree, so a
pull in another checkout moved that revision past the copy a stale worktree
still held: the unedited copy read as an edit, and push offered it as
modified, ready to send the teammate's change back as the old version.

Push now compares with the revision this checkout last synced, from its
lastPullByWorkspace entry (checkoutKey is exported from pull.ts), and falls
back to the shared lastPullRev for a checkout with no entry. For that entry to
survive, a pull at a new team revision no longer drops the other checkouts'
records: a checkout recorded at an older revision already misses the fast
path. When the pull finds lastPullRev cleared, it resets the other records
to an empty rev (FORCED_FULL_SYNC_REV), which matches no revision, so a forced
full sync reaches every checkout, single-repo mode included, while each record
keeps its push bases. Each full sync keeps only the records
of checkouts `git worktree list` still reports, and keeps them all when the
list comes back empty, so a removed or re-created worktree's entry does not
pile up.

The sync itself moves the unedited copies to the team repo's revision, so
push then adds that revision to the entry's pushBaseRevs (newest first, the
20 newest kept) and the next push compares with them; otherwise a copy synced
to R2 read as an edit against R1 once a teammate published R3. Push leaves the
entry's rev alone, since the pull fast path reads it and the checkout still
lacks that revision's docs and agents; the next pull rewrites the entry
without pushBaseRevs. The sync accepts a copy at any of pushBaseRevs or rev (a
skill only when all its files are at one of them), so a copy it left alone as
edited is synced again once the member undoes the edit, back to whichever
version a sync gave it. The base is recorded even when the sync stops
partway, which now warns, since the copies it did not reach still match an
older base; a revision push cannot save stops the push before the scan. A
checkout with no entry (a new worktree, or one last pulled by an older CLI)
can only sync against the shared lastPullRev, which may be another
checkout's or cleared: when the scan lists a team rule or skill as modified,
push stops before creating a branch and asks for a pull there, warning that
the pull replaces those files. A rule this machine placed does not count, and
config-only pushes and new resources go through.
2026-09-25 12:04:16 +08:00
Saul Moro c7723d652b fix(hooks): keep a removed worktree's hook events in its project (#810) (#824)
A hook resolves its scope from the payload's cwd, and resolveConfigForDir
answers the user scope for a directory that no longer exists. So once a
session's worktree was removed, its remaining events (tool_use, SessionEnd,
Stop) and skill uses were recorded under the user scope, which then counted
the session and reported the skills to its team, or were dropped when there
was no user scope. The project lost the session's last snapshot.

resolveHookConfig (dashboard-collector.ts) is the one resolver for the
hook dispatcher and the legacy dashboard-report, track and track-slash
entry points. For an existing (or absent) cwd it is resolveConfigForDir, as
before, and reads nothing else. For a cwd that is gone it reads this
session's last event that recorded a dataHomeKey, once per process, preferring
the events recorded at that same cwd (a detached Stop can run after the
session moved on to another repo), and
resolves the config at that event's projectAnchor, the main checkout,
which still exists (for a bare repo, whose anchor is the git directory,
at one of its worktrees that still exists). It uses that config only when it is still the scope the
recorded dataHomeKey names, so a worktree's own legacy .teamai never becomes
the main checkout's scope. If that config exists but cannot be read, the
event is dropped rather than given to the user scope (#748). With nothing
to match (no events, events from before #809 without an anchor), it is
today's answer.

The dispatcher's track and track-slash handlers now use the dispatcher's
config instead of resolving their own, and eventProjectAnchor gives an
event whose cwd is gone the session's last anchor, as process_exit does.
The legacy track-slash looks skills up under the resolved scope's tool
roots before the cwd's. The share reminder's gates (contribute-check on
Stop, pending-hint on the next prompt) ask about hookScopeDir, the
directory resolveHookConfig resolves from, so a removed worktree's
session gets the project's reminder settings, not the user scope's. The
legacy `teamai contribute-check` command gates the same way. The hook
session id has one implementation, deriveDispatchSessionId in
utils/session-id.ts, shared by the dispatcher and the event writers.
2026-09-25 11:51:40 +08:00
Saul Moro 4a65e3f676 fix(import): publish the learning import --from-mr extracts (#823) (#825)
`import --from-mr` wrote its learning into the teamai-learnings worktree,
then pushed with autoPushViaMR, which commits `.` in repo.localPath: the
knowledge clone, another checkout. That found nothing to commit, so the
learning stayed untracked on this machine and never reached the team,
while the command still reported the push step as done.

The draft now goes into the contribution queue, and a "Publish learning"
step calls publishQueuedLearnings, the path `teamai contribute` uses: it
commits and pushes the queue on teamai-learnings and drops an entry once
it is on origin. When publishing fails the learning stays queued, the step
says so, and the next `teamai pull` publishes it. As in contribute, the
queued file takes contribute's name (a random suffix keeps two learnings
with the same title and day apart), the recall index is rebuilt after the
publish attempt, the supersede check also reads the queue, and a read-only
(HTTP) source is refused up front instead of queueing a learning nothing
can publish; --dry-run and --output still work there. "Push changes via
MR" is left for the teamwiki update it was also for.

The learning also lands where contribute puts it: resolveLearningsSubdir
(now exported) picks learnings/<namespace>/ when exactly one active project
declares a learnings namespace, else the shared root. It used to go to the
root, where every project's members recall it.

Also, from the same follow-up issue:
- wiki slug: the main checkout's root takes its repo's name too, so one
  opened through a differently named symlink writes the same evidence as
  its worktrees. Subdirectories keep their own name.
- repo labels: a path is not qualified into a label a remote-form key
  already has (github.com/acme/api vs /x/acme/api), so the two no longer
  merge in `stats --by-repo`. The fallback is the repo's directory, so a
  bare repo's keys still share one row.
- local-agent tests use a session id unique per run: the hint markers are
  machine-wide files in os.tmpdir() keyed by session id, and overlapping
  runs deleted each other's.
2026-09-25 11:50:20 +08:00
Saul Moro c73d22147d fix(report): each scope reports its own dashboard sessions once, against its own snapshots (#785, #786) (#791)
* fix(report): each scope reports only the dashboard sessions recorded in it (#785)

Every scope read one machine-wide events.jsonl and picked its sessions out
by cwd prefix. The user scope excluded nothing, so a user-scope pull
reported every project's sessions (and, through the shared reported
snapshots, took them from the project's own report); Copilot sends no cwd,
so a project never reported its Copilot sessions; and a raw cwd under a
symlink or /tmp never matched the realpath'd projectRoot.

The hook now stamps each event's dataHome with the data home of the scope
the dispatcher resolved (the key the per-scope usage file already uses), and a
report keeps only its own scope's events, comparing realpath'd keys. A
project also owns its in-repo .teamai key, where hooks record until
migration moves it to a partition. Events written before this carry no
dataHome: a project keeps those whose realpath'd cwd is under its root, the
user scope never reports them. The log stays machine-wide for the
dashboard UI, stats --by-repo, session save and the contribute check.

Removes the excludeProjectRoots option, which pull only ever passed as []
(the user target exists only when no project config resolved), and the
projectRoot option now carried by selfConfig. The usage guide documents how
to remove by hand a skill an earlier release pushed into stats/<user>.yaml
from another project.

* fix(report): address pre-review findings (#785)

- Events record `dataHomeKey`, a hash of the realpath'd data home, instead
  of the path. A Copilot event persisted a workspace path through its data
  home (the raw root for a non-git project, the path-derived partition name
  otherwise), breaking the path-free Copilot contract from #666.
- A data home that no longer exists (an in-repo .teamai removed after
  migration) keys through its parent's realpath, so it still matches the key
  recorded while it existed.
- A non-git project's root is realpath'd before older events' cwd is matched
  against it, as the cwd already was.
- A key that is not a string (a hand-edited log) counts as absent instead of
  throwing and skipping the whole report.
- The legacy `dashboard-report` command's stamping is asserted.
- CHANGELOG and the comment say teamai does not record Copilot's cwd, not that
  Copilot sends none.

* docs(report): place the stats cleanup under usage reporting (#785)

The manual `stats/<user>.yaml` cleanup sat under single-repo mode, but the
pre-#748 leak hit every team with a git-kind repo, so it moves to "Usage
reporting" and notes where an `http` team repo keeps the file. The guide
also says the scope key is per event: hooks that run outside the project
(a worktree removed before the session ends) report to the scope they ran in.

* docs(report): name where unattributed sessions go (#785)

The CHANGELOG now says a session in a directory that resolves to no project
(a non-git project's subdirectory, a submodule or nested clone) is the user
scope's, as for skill usage. The usage guide drops the line on http team
repos: pull does not report usage to them, so no stats file there needs
cleaning.

* fix(report): each scope keeps its own reported dashboard snapshots (#786)

The report sends per-session deltas against reported-*.json snapshots that
every scope shared. A session whose events belong to two scopes (a cd into
another project mid-session) was then reported by the first scope, and the
second compared its own part with the first scope's totals and sent nothing.

Each scope now keeps its snapshots in <dataHome>/dashboard/, and the user
scope, whose data home holds the shared files, in user-reported-*.json. The
first time a scope needs one it copies the shared file, so the first report
after the upgrade sends nothing already reported; after that it reads only
its own. The user scope moves too, unlike the ticket proposed: had it kept
writing the shared file, a project seeding later would copy the user scope's
part of a split session and report nothing for its own. The shared file is
no longer written, except by an earlier release after a rollback, which only
a scope not yet seeded reads.

* fix(report): report each dashboard session once, from the scope it started in (#785, #786)

A Stop carries the whole transcript's totals (prompts, tokens,
interventions, request cost). Filtered per event, a session that moved into
another scope mid-session was reported whole again by the scope holding the
later Stop: 3 user-scope prompts then 2 in P reported 3 to the user team and
5 to P. Each session is now decided once, by its first keyed event, and
reported whole by that scope. This replaces #786's "a split session reaches
both teams with its part"; per-scope snapshots stay, so a session ID another
scope already reported (Copilot's PID fallback) still counts as new.

Unkeyed sessions from before the upgrade are decided by their first cwd. The
user scope now takes those whose directory still exists and resolves to it
(resolveConfigForDir, the dispatcher's rule) instead of dropping its whole
backlog; no cwd, or one removed since, is still no scope's.

The Copilot test also runs a payload without cwd from a hook in the project.

* fix(stats): read the scope's own dashboard filter and snapshots (#785, #786)

`teamai stats` (#771) still called filterEventsByScope with the old
{ projectRoot, excludeProjectRoots } options, synchronously, after #795
made it async and keyed by the scope config, so main no longer type-checks
and stats-scope fails. It also subtracted the shared reported-*.json, which
no scope writes since #786.

stats now filters with the config it resolved and subtracts that scope's
own snapshots (readReportedInterventions / readReportedPromptTokens, the
report's readers), so what it shows matches what pull reports. The user
scope leaves a project's older sessions out, as the report does (#785); the
stats-scope case that pinned "no exclusion in the user scope" now expects that.

* fix(stats): address CI review (#785)

A session ID now names one run up to its session_end or process_exit.
A PID-fallback ID (Copilot) comes back for a later run, maybe in another
scope, and the log keeps the ended run below the compaction threshold, so
grouping by ID alone gave the later run to the first run's scope. Each run
is still decided whole by its first keyed event.

Events written by main since #795 record the data home as a path
(`dataHome`); the report now keys them the way the writer derives
`dataHomeKey`, so pending Copilot sessions (no cwd) are not dropped.

* fix(stats): address CI review (#785)

A later run of a reused session ID (Copilot's PID fallback) was decided
on its own but returned under the same ID, so aggregation and the
per-scope snapshots merged two runs in one scope back into one session.
The filter now returns a later run as `<id>@<first event timestamp>`;
the first run keeps the bare ID, so existing snapshots still match.

An unkeyed event's cwd under a project root counted even when the
directory was gone (realpath fell back to the raw path). It now counts
only while it exists, as the docs and the user-scope rule already say.

* fix(stats): address CI review (#785)

Run identity no longer depends on which earlier runs compaction kept:
every run is `<id>@<first event timestamp>`, so a reused PID-fallback ID
is a new session even when the scope's snapshot still names the run
compaction dropped. Snapshot entries keyed by the bare ID (written by
earlier builds) are adopted by the first run of that ID in the log, so
the upgrade re-sends nothing; the next snapshot holds only run IDs.

An unkeyed event's cwd is now owned by the scope resolveConfigForDir
resolves it to, for projects as for the user scope, so a nested clone
under a project is no longer reported by both. The lexical root matcher
and its string-level tests go; the cases move to real repositories.

* fix(stats): address CI review (#785)

adoptBareKeys() read a legacy bare `pid-N` snapshot entry as the first
run's, but only in memory: the success writes merge into the file, and
with nothing new to report nothing was written, so the bare entry stayed.
Once compaction dropped that run, the next run reusing `pid-N` read it and
was suppressed. The report now writes each snapshot as soon as a bare entry
is retired, under the run ID only, even when there is no delta.

* fix(stats): address CI review (#785)

A bare snapshot entry is given only to a run an earlier release recorded
(its first event has no dataHomeKey). Only earlier releases wrote bare
entries, and a seeded one may be another scope's run under a reused
PID-fallback ID, so a run this release recorded takes none. A marker of
the seed time would miss the common case: a scope seeds at its first
report, usually the pull its first session's SessionStart triggers.

A second end of a run with nothing recorded since the first (the
dashboard monitor's process_exit after SessionEnd) joins the run it
closed instead of opening a terminal-only run counted as a session.

* fix(stats): address CI review (#785)

A scope's first snapshot is seeded only with the shared entries of its
own runs in the log, under their run IDs, and none for a run recorded
with a dataHome path: that release already kept per-scope snapshots, so
a shared entry under the same ID is another scope's. An unmatched entry
is dropped instead of copied, so a later reuse of the ID cannot inherit
it.

The dashboard monitor records processExitAfter, the last event it
observed, and the scope filter closes only that run. A delayed exit
appended after the next run of the same ID began no longer ends it and
splits it in two; an exit whose run compaction dropped is ignored.

* fix(stats): address CI review (#785)

An earlier release summed every run of a reused ID under its bare
snapshot entry, but only the first retained run adopted it, so the next
one was reported again. Each of those runs in the log but the last is
now taken as reported at its own totals and the last takes the entry,
in the report, in teamai stats and in the seed from the shared file.
The last run is undercounted by at most the other runs' share, once.

A session_start on a fallback ID from another monitorPid than its open
run's begins a new run, so a run that crashed with no dashboard running
no longer takes the next invocation, maybe another scope's. A tool's own
ID is not split: Claude fires SessionStart again on resume, in a new
process, and its Stop carries the whole transcript.

* fix(stats): address CI review (#785)

An end splits runs only on a fallback ID (pid-…). A tool's own session
ID is one session whatever ends it records: claude --resume continues it
in a new process, and its Stop carries the whole transcript, so a second
run counted it again, maybe in another scope.

* fix(stats): address CI review (#785)

A tool's own session ID is keyed by the ID itself again, as on main,
not by its first event's timestamp, so a session resumed after
compaction dropped its events still reads what its scope reported.
Only PID-fallback runs carry the timestamp.

A bare fallback entry is the sum of the runs of its ID in the log at
the earlier release's last report, and compaction keeps or drops an
ID's runs together. Those runs now consume it in log order, each up to
its own totals, so a later run that release never reported is sent
instead of taking the whole entry. The prompt-token snapshot decides
which runs it covered; interventions and daily follow it, and the first
run always takes a share.

* fix(stats): address CI review (#785)

Seeding a scope from the shared snapshot splits the whole log into runs,
lets every scope's runs of a bare ID consume its entry in log order, and
keeps the shares of the scope's own runs. The shared file summed every
scope's runs, so one scope consuming it alone could spend another
scope's baseline and suppress its own pending run.

The scope that first reports a tool's own session ID records itself in
~/.teamai/dashboard/session-owners.jsonl (the ID and its data home key,
no path), and a recorded session stays that scope's wherever it is
resumed, after compaction dropped its events too.

A dashboard started before processExitAfter existed reads the log and
appends its exit in one pass, so an unannotated exit less than one PID
check after the open fallback run began belongs to the run closed before
it instead of closing the next invocation.

* fix(stats): address CI review (#785)

A run taking its share of an earlier release's summed daily snapshot
keeps its own success and correction flags: the sum's are no single
run's (a successful run and an interrupted one sum to unsuccessful), so
an adopted run changed sessionsSucceeded without sessionsEnded.

An unannotated process_exit from a dashboard started before
processExitAfter no longer ends the open fallback run when more events
of that ID follow before the next start: a dead process records nothing
more, so it was observed before that run and belongs to the run closed
before it. This replaces the 15 s window, which a delayed callback or a
skewed clock could miss.

* fix(stats): address CI review (#785)

session-owners.jsonl is first written from the per-scope snapshots an
earlier release left: a tool's own ID in the user scope's or a
partition's prompt-token snapshot is that scope's, so a session main
reported in P, compacted and resumed in Q, stays P's instead of being
reported again to Q. An ID the shared snapshot also holds is left out:
main copied the shared file into every scope, so it names no owner, and
every scope already has its baseline. The file is created exclusively,
so a concurrent report in another scope reads the one written first.

* fix(stats): address CI review (#785)

Owner migration reconciles every per-scope baseline of an ID: a tool's
own ID in any of a scope's three snapshots is the scope's that holds its
greatest total (prompts, then tokens). A session main split per event
holds only part of it elsewhere, and a scope may have reported past the
shared total it was seeded with, so neither the first holder nor
leaving shared-held IDs out was right; a session reported with no
prompts, only its intervention count, is found too.

Besides the user scope and the partitions, it reads a project whose data
home is in its workspace that a session still in the log leads to, and
each report records the IDs of its own snapshots that no owner claims
yet, for such a project the log no longer leads to.

* fix(stats): address CI review (#785)

Owner migration assigns no owner when the greatest total ties across
scopes: main copied the shared snapshot into every scope, so equal
totals show only that copy, and each scope already holds the baseline.
A report records an ID of its own snapshots only when they show it
reported it (absent from the shared snapshot, or past its total there),
so a copy no longer claims it either.

A crashed fallback run a start from another process supersedes counts
as the run closed before it, so a late unannotated exit of it no longer
closes the new run.

* test(stats): pin a pre-upgrade exit reported before the next run's first prompt (#785)

The run split is recomputed from the whole log on every report, so once
the next run's first prompt follows the unannotated exit, the exit is
the earlier run's and the next run keeps its ID: the second pull
reports only its delta, not another session.

* fix(stats): give a compacted session resumed elsewhere to the project its transcript started in (#785)

Once compaction dropped every event of a project whose data home is in
its workspace, nothing outside it pointed to it, so a resume of its
Claude session in another project reported the transcript there again.
The transcript itself records where the session started: a Claude
transcript keeps its first cwd when resumed from another project (the
resume appends to the same file), as a Codex rollout keeps its
session_meta. Hooks now record transcriptPath on UserPromptSubmit and
SessionEnd as well as Stop (not SessionStart, whose path on such a
resume names a file that never exists; never Copilot's). A tool's own
session with no owner is the scope's that its origin resolves to, when
that scope's snapshots already hold it; otherwise it is decided as
before.

* fix(stats): address CI review (#785)

A session main split across scopes per event is credited once with
every part it reported: for each scope its `dataHome` names, the
shortest prefix of its events whose metrics reach its snapshot, and the
owner takes the metrics of their union as reported when they exceed its
own entry. Parts counted before any Stop carried the transcript's total
are no longer sent again by the owner, and cumulative Stops are not
credited twice.

A Copilot session with an explicit ID is traced to where it started by
Copilot's own session log, found by the session ID (TeamAI stores no
path of it, #666): its session.start context names the directory.

Compaction keeps a session whose tool process is still running, so a
run that an exit from a dashboard before processExitAfter marked stopped
keeps its start and its ID.

* fix(stats): address CI review (#785)

Owner migration takes a scope's entry as evidence only when its
snapshots show it reported the ID: the shared snapshots (interventions
included) hold none of it, or the scope is past their total. Main copied
the shared file into every scope it ran in, so a copy, even the only
one, names no owner, and the per-report recording follows the same rule.

A session main split across scopes whose events are gone is credited
from the parts' snapshots: a part whose daily entry shows a Stop holds
the transcript's cumulative total, so the greatest counts once; a part
with no Stop counted its own prompts, which add; intervention counts
add, tokens take the greatest. The credit rides on the owner's line in
session-owners.jsonl (numbers only) and is applied once as its baseline.

* fix(stats): keep a tool's own sessions in the first snapshot, parse legacy entries (#785)

Seeding a scope's snapshot from the shared one kept only the runs still
in the log, so a session reported before #795 and compacted before the
scope's first pull was sent again in full when resumed. Only fallback
entries need that filter, against a reused PID; a tool's own session ID
is one session, so its entry is copied whole, as main did.

Splitting a bare entry across runs read the snapshot entry as typed,
and one without `tokens` (hand-edited or truncated) threw and skipped
the whole report; the prompt-token and intervention shares now parse it
as the owner-migration path already does.

* fix(stats): report a resumed Codex rollout after compaction dropped the earlier one (#785)

A Codex build that writes a new rollout per resume restarts its
transcript counters, and the session summed only the rollouts still in
the log. Once compaction dropped rollout A, a resumed rollout B with
smaller counters was compared against A's reported total and reported
nothing until it passed it; routing the session back to the scope it
started in made that loss reach the resume in another scope too.

The prompt-token snapshot now keeps each rollout's reported prompts and
tokens under a hash of its path (no path stored), and a rollout that is
gone keeps its reported totals in the session's sum, so B is reported in
full. A session's prompts also sum its rollouts' Stop counts, which
restart per rollout like the tokens. An entry from before is compared
as a whole once, then kept per rollout.

* refactor(stats): move dashboard scope attribution and session owners out of team-push (#785)

No behavior change. src/dashboard-scope.ts holds which scope reports a
dashboard session (the log split into runs, each given whole to the
scope it started in, and the transcript origin); src/session-owners.ts
holds the machine-level owners index, its seeding from earlier
snapshots, and the snapshot files it reads. team-push.ts keeps the
snapshot adoption, deltas and push, and one reportedBaselines() now
serves both the report and `teamai stats`, which repeated the adoption
sequence.

* test(stats): real CLI resume of a compacted session from a workspace-data project (#785)

A non-git project W keeps its data home in its workspace. W reports a
Claude session; with no owners index and every W event compacted, the
session is resumed in git project Q through the real hook dispatcher,
appending to W's transcript. Q reports only its own session and W the
resumed turn; on a build without the transcript origin, Q reports both.
The fixture gains a second project and hooks sent as the installed
ones send them.

* fix(stats): credit a split session's Stop-derived interventions once (#785)

Interruptions and tool rejections come from Stops, which carry the
transcript's cumulative counts, so a compacted split session's credit
takes the greatest part, as it does for tokens; summing them made the
next cumulative Stop report nothing. Corrections are counted per prompt
in each part's own events, so they still add.

* fix(stats): place a compacted split session's parts by its transcript (#785)

A split session's credit added a part with no Stop to the greatest
cumulative Stop, which already counts that part when it came before the
Stop: after 3 prompts in P and a cumulative Stop of 5 in Q it credited
8, and the next Stop of 6 reported nothing. The credit now keeps each
part (scope key, prompts, whether it ended in a Stop; numbers only), and
the owner places them by the session's transcript, which keeps every
prompt in order with the directory it was typed in: the Stop covers the
first prompts, and only the part's prompts after those add. With no
transcript to place them, they all add, as before.

The Stop scan's human-turn test is now isHumanPromptEntry, shared by
both, so the two count prompts alike.

* fix(stats): keep a dropped Codex rollout's totals for daily and interventions, and migrate whole entries (#785)

An entry from before rollouts were kept is one total. An earlier
release rewrote every session in the log on each report, so it covers
the rollouts begun by the time its file was last written, read before
this report writes it: those still in the log consume it in order, what
is left is the dropped rollouts', kept as one prior rollout, and a
rollout begun later is new. Rollout B after a compacted A is no longer
compared against A's total and lost.

A rollout also keeps its Stop's interruptions and rejections, and its
dropped totals now reach the intervention and daily sums too, not just
prompts and tokens: daily prompt turns and intervention counts of a
resumed rollout were compared against the dropped one's.

* fix(stats): keep every metric of a dropped Codex rollout, with or without tokens (#785)

A Codex session is now kept per rollout whenever its Stops name a
rollout, not only once a Stop carries a token record, so a tokenless
resumed rollout is not compared against the dropped one's totals. Each
rollout also keeps its corrections (a correction goes to the rollout of
its prompt), its active time (each gap to the rollout of the event it
ends at) and its request costs, and a dropped rollout adds them to the
intervention and daily sums, with its cache tokens from its tokens.

The prompt-token snapshot, which holds the rollouts, is written with any
delta, so a rollout whose rejections alone moved keeps its new totals.

* fix(stats): sum a Codex session's rollout costs and keep a dropped rollout's failure (#785)

The daily snapshot took the request costs of the latest rollout only,
so with rollout A still in the log a rollout B was compared against A's
costs and clamped; a Codex session's daily costs now sum its rollouts.

Each rollout also records whether it failed (an error, an interruption
or a correction). A dropped rollout that failed keeps the session
unsuccessful, and one with a correction keeps it corrected, so a clean
later rollout does not turn it into a success.

* fix(stats): keep modern Codex rollouts, and their submit-counted prompts, per rollout (#785)

A Codex session whose tokens come from the thread-level counter
(tokenScope session) was not split into rollouts, so its prompts,
interventions, active time, costs and failure were compared against a
dropped rollout's. It is now kept per rollout like the others; the
counter already spans the rollouts, so no rollout holds tokens of its
own and the session total stays that counter's.

A Codex Stop may count no prompts, so a rollout's prompts are its
Stop's count or else its own submits: a dropped rollout's submit-counted
prompts are no longer lost.

* fix(stats): no legacy tokens on a spanning Codex counter; teamai stats writes no seed (#785)

A whole entry an earlier release left became a prior rollout carrying
its tokens, which were then added to a thread-level counter that already
holds them: rollout B's counter at 530 after A's 500 re-sent 500. A
session whose counter spans its rollouts now takes no tokens from a
dropped or prior rollout.

`teamai stats` only reads, but seeding a scope's first snapshot wrote it
with the current time, which a later report reads as the time an entry
from before covers, taking a rollout begun earlier as reported. A read
that does not persist now writes no seed, and a written seed keeps the
shared file's time.

* fix(stats): read a legacy daily entry's session cost fields as its day's costs (#785)

parseDailySnapshot() dropped the top-level pricedRequests, costMicros,
cache tokens and priceVersion a daily entry from before per-day costs
held, so an entry from before rollouts were kept lost its cost in the
prior rollout, and a later rollout's cost was compared against it and
omitted. They are now read as the session day's request costs, as
computeDailyStatsDelta already reads them.

* fix(stats): keep every Codex variant per rollout, and an older Stop's request cost (#785)

Rollout tracking recognized only `codex`, not `codex-internal` or
`tcodex`, which write the same rollouts; it now uses isCodexTool(). A
rollout's cost was read from requestDaily only, so an older Stop's
requestMetrics left the rollout without cost, and the daily snapshot,
which sums rollouts, omitted it; it is now that Stop's day's cost, as
outside rollouts.

* fix(stats): keep a Codex rollout's latest Stop by timestamp (#785)

A rollout's prompts, interventions and request costs took the last Stop
appended, though background Stop handlers may append an older scan
after a newer one, which then replaced the newer totals. They now keep
the latest Stop by its timestamp, as the rollout's tokens already do.

* fix(stats): an entry from before covers a running Codex rollout only as far as it had got (#785)

Migrating a whole entry from before rollouts were kept consumed it with
each covered rollout's current totals, so a rollout begun before the
entry was written but grown since had its later prompts taken as
reported: an entry of 6 (A's 5, B's 1) with B now at 3 reported nothing.
It now consumes it with each rollout's totals as of the entry's write,
the metrics of the events up to then; what a rollout has done since is
new.

* fix(stats): credit a split session counter by counter; read an old entry's cutoff before its push (#785)

Both credit paths applied only when the parts' prompts exceeded the
owner's, so a part that reported more active time, tokens or costs with
no more prompts was sent again by the owner. The owner's entry is now
raised counter by counter to at least the credit.

An earlier release wrote its snapshot after the push, so events that
arrived during the push predate the snapshot's time without being in
it. The team stats file in the scope's reports checkout was written
after that report read the log and before the push; the earlier of the
two times is now the cutoff an entry from before covers.
2026-09-25 10:36:37 +08:00
Saul Moro 5e5b86d9e9 fix(stats): count every worktree of a repo as that repo (#809) (#813) 2026-09-25 01:39:23 +08:00
Ruifeng Xue 49cf3fdd10 fix(docs): remove stale local documents during pull (#817) 2026-09-25 01:25:11 +08:00
Saul Moro a725574b34 fix(usage): cap usage.jsonl in scopes that never report (#788) (#790) 2026-09-24 23:43:42 +08:00
Saul Moro 9f81ae6751 fix(pull): deliver team resources to a worktree added after the last pull (#807) (#811)
state.json lives in the shared project partition, so a new worktree matched
the revision another checkout recorded and took the "Already synced" fast
path, leaving it without the team's skills, rules, agents and docs. The
shared tool targets also made two checkouts with different tool directories
force a full sync on each other on every pull.

Record the revision and targets per checkout in lastPullByWorkspace, keyed by
the checkout path plus the identity of its .git entry so a worktree re-created
at the same path does not inherit the old record. The fast path still requires
the shared lastPullRev, which exclude, tags, roles, projects, init and
bootstrap clear to force a full sync, and a pull that records a new revision
drops the other checkouts' records so every checkout does its own full sync.
2026-09-24 22:22:38 +08:00
Saul Moro ec56a67c1b fix(recall): search nothing in a project whose config cannot be read (#796) (#798)
* fix(recall): search nothing in a project whose config cannot be read (#796)

Detection skips a project config it cannot read and returns what loads
next: a legacy .teamai/ behind a broken partition, which may name another
team, or the user scope. recall searched that knowledge, recorded recalled
counts for it, and `recall --check` answered for it; with nothing behind
the broken file it printed NOT_RELEVANT, so the recall subagent told the
member the team had no knowledge and nobody learned the config was broken.

recall() now listens for the unreadable config before anything else,
searches and records nothing, prints the problem with
BROKEN_CONFIG_ADVICE and exits 1, `--check` included. A silent caller
records it in debug.log only, the rule pull follows since #784. The
teamai-recall agent relays that line instead of skipping the precheck.

* fix(recall): address pre-review findings (#796)

- The relayed line ends with "move it aside and run `teamai init`", and
  the main conversation may not have loaded the teamai skill that asks
  for consent first. The recall agent now tells it to show the line to
  the user and not act on it without their consent.
- Tools that run `teamai recall` directly (the Bash method of the recall
  rule, deployed to every tool) get the same instruction.
- CHANGELOG: only the subagent a pull from this release deploys relays
  the line; a project that broke before the upgrade keeps the old one
  until a pull succeeds there.
- The legacy-team test also asserts no votes land in that team's repo.

* fix(recall): address pre-review findings (#796)

- CHANGELOG: the entry covers `teamai recall <query>` and `--check`. The
  recall subcommands (enable, disable, status, feedback, maintenance,
  promote) still resolve their scope as before; that is a follow-up.

* fix(recall): address CI review (#796)

Reject a missing query before resolving the project, so a bare
`teamai recall` runs no detection (and no self-mode bootstrap). An empty
`--check` still resolves first: it must refuse rather than print
NOT_RELEVANT in a project whose config cannot be read.

Drop the silent branch: `recall` has no --silent flag and no caller
passes `silent`, so it was a contract nothing could invoke.

* test(recall): follow #787's per-scope votes (#796)

#787 moved recalled counts from the shared ~/.teamai/votes/ into each
scope's votes directory, so the #796 tests look for any votes directory in
the sandbox. #787's broken-project recall test expected a search to run;
#796 searches nothing there, which it now asserts, while its checks that no
scope received a vote stay.
2026-09-24 20:54:28 +08:00
Saul Moro 1fd400ecfa fix(pull): sync nothing in a project whose config cannot be read (#784) (#792)
* fix(pull): sync nothing in a project whose config cannot be read (#784)

Detection skips a project config it cannot read and returns what loads
next: a legacy .teamai/ behind a broken partition, which may name another
team, or the user scope. pull() deployed and reported for that team, and
the session-start hook did so on every session (reports-wt/ and
learnings-wt/ appeared in the legacy .teamai/).

pull() now listens for the unreadable config, syncs no scope, prints the
problem with BROKEN_CONFIG_ADVICE and exits 1. A silent pull (the
session-start hook, or a pre-dispatch hook running `teamai pull --silent`)
records it in debug.log only. Agent-root seeding and the package hint
refuse the same way, so a session start there does nothing. Hooks and
usage already follow this rule since #748. The message trimming detectTeam
used moves to config.ts as describeUnreadableConfig so both share it.

* fix(pull): address pre-review findings (#784)

- The session-start handler returns when the dispatcher resolved no
  config for the hook's cwd, which is what an unreadable project config
  resolves to since #748. That one guard replaces the unreadable-config
  sinks added to seedProjectAgentRoot and the package-hint context, and
  follows the #769 contract that handlers read their scope from the
  dispatcher. The handler tests that exercise cwd routing now pass a
  resolved scope; a new one pins that nothing runs without one.
- CHANGELOG and usage guide (en, zh-CN): a session start there runs no
  pull; only `teamai pull --silent` from a pre-dispatch hook writes the
  reason to debug.log.
- skill-data troubleshooting: what `Nothing was synced` means, and that
  moving the config aside and re-running init needs the user's consent.

* fix(pull): address CI review findings (#784)

- The session-start pull is registered with `requiresConfig` instead of
  returning early inside the handler: the dispatcher drops it wherever no
  config resolves, which covers an unreadable project config (#748), and
  spawns no detached pass for it. Where no teamai config exists at all
  it did nothing on main either (no scope to pull, no project root to
  seed, no config for a package hint). The #748 registry test and the
  docs no longer list it as machine-level work.
- `teamai pull --silent` exits 1 on the refusal too. Pre-dispatch hooks
  run it as `… 2>/dev/null || true` (`; exit 0` on Windows), so hosts
  still see success.
- The dispatch-scope test asserts the pull is skipped and resets the
  pull mock it queues.
- skill-serving design doc: `teamai pull` now reports an unreadable
  project config too. skill-data troubleshooting: `teamai doctor` can
  pass there.

* fix(hooks): still pull at session start where teamai is not set up (#784)

A null config from the dispatcher means either "no teamai here" or "the
project config cannot be read". Gating the session-start pull on
`requiresConfig` stopped it in both; only the second must stop it. The
handler now asks `findUnreadableProjectConfig` for the hook's cwd when
no config resolved (a cwd that no longer exists holds none) and runs
nothing when it reports a file. Everywhere else it runs as on main, so
the docs list it as machine-level work again.
2026-09-24 20:07:24 +08:00
Saul Moro 8cee7ab23e fix(migrate): keep the legacy .teamai/ while the partition config cannot be read (#797) (#799)
* fix(migrate): keep the legacy .teamai/ while the partition config cannot be read (#797)

planMigration took a partition config.yaml that merely existed as a built
partition and planned a retire-only cleanup, so the first init/pull/push after
the partition file broke renamed the legacy directory to .teamai.bak although
it held the only config that still loaded. Only a partition config that
detection's own reader (readConfigFrom) accepts now counts as built; one that
exists but cannot be read plans nothing, and the next write command after the
fix retires the legacy dir as before. The re-check under the sync lock in
runMigration uses the same rule, so a broken file that appears between planning
and locking skips instead of retiring.

* fix(migrate): address pre-review findings (#797)

- Warn with the file and the first line of the reason when an unreadable
  partition config holds the migration back. The skip was silent, so a member
  had no signal which file to fix, including under --dry-run. The text says what
  happens next and hedges for a file caught mid-write.
- Stand down when the partition dir exists without a config.yaml. Keeping the
  legacy dir made "move it aside and run teamai init" (BROKEN_CONFIG_ADVICE)
  reach the full copy, which removes the partition dir before renaming the
  staged copy in and so deleted its pending learnings, env and clone. The
  re-check under the lock stands down on an existing partition dir too.
- Decide built / unreadable / absent in one helper that uses detection's own
  onUnreadable report, so the plan and the re-check cannot drift.
- Tests: a real YAML syntax error, a partition config that is not scope:
  project, the moved-aside sequence, a fresh project still planning 'full', and
  the re-check retiring when a readable partition appears after planning.
- Design doc and CHANGELOG: list every cause detection reports and the guard.

* fix(migrate): address CI review (#797)

The upgrade note in both usage guides promised an unconditional migration;
it now says a partition whose config.yaml cannot be read, or is missing,
keeps .teamai/ and what the member does next. The full copy's re-check
under the sync lock logged only at debug level when it stood down; it now
gives the same actionable warning as the planner.
2026-09-24 19:20:06 +08:00
Saul Moro 352cfc4ccc fix(report): each scope keeps its own reported dashboard snapshots (#786) (#795)
* fix(report): each scope reports only the dashboard sessions recorded in it (#785)

Every scope read one machine-wide events.jsonl and picked its sessions out
by cwd prefix. The user scope excluded nothing, so a user-scope pull
reported every project's sessions (and, through the shared reported
snapshots, took them from the project's own report); Copilot sends no cwd,
so a project never reported its Copilot sessions; and a raw cwd under a
symlink or /tmp never matched the realpath'd projectRoot.

The hook now stamps each event's dataHome with the data home of the scope
the dispatcher resolved (the key the per-scope usage file already uses), and a
report keeps only its own scope's events, comparing realpath'd keys. A
project also owns its in-repo .teamai key, where hooks record until
migration moves it to a partition. Events written before this carry no
dataHome: a project keeps those whose realpath'd cwd is under its root, the
user scope never reports them. The log stays machine-wide for the
dashboard UI, stats --by-repo, session save and the contribute check.

Removes the excludeProjectRoots option, which pull only ever passed as []
(the user target exists only when no project config resolved), and the
projectRoot option now carried by selfConfig. The usage guide documents how
to remove by hand a skill an earlier release pushed into stats/<user>.yaml
from another project.

* fix(report): each scope keeps its own reported dashboard snapshots (#786)

The report sends per-session deltas against reported-*.json snapshots that
every scope shared. A session whose events belong to two scopes (a cd into
another project mid-session) was then reported by the first scope, and the
second compared its own part with the first scope's totals and sent nothing.

Each scope now keeps its snapshots in <dataHome>/dashboard/, and the user
scope, whose data home holds the shared files, in user-reported-*.json. The
first time a scope needs one it copies the shared file, so the first report
after the upgrade sends nothing already reported; after that it reads only
its own. The user scope moves too, unlike the ticket proposed: had it kept
writing the shared file, a project seeding later would copy the user scope's
part of a split session and report nothing for its own. The shared file is
no longer written, except by an earlier release after a rollback, which only
a scope not yet seeded reads.
2026-09-24 19:18:09 +08:00
JinandClaude Opus 5.5 97be092633 feat(projects): add admin commands to manage the projects manifest (#756) (#774)
`manifest/projects.yaml` could only be edited by hand. Add
`teamai projects add/update/remove`, mirroring `roles add/update/remove`:
each edits the manifest, validates it with the same checks a load applies,
and opens a PR, with --dry-run to preview. The first `add` creates the file.

- `add --namespaces` sets one namespace set on every resource type.
- `update --add-namespaces/--remove-namespaces` edits each type's own list,
  so hand-edited per-type layouts survive; emptying a project is refused.
- `remove` warns about directories that still have the project active.

The pull/branch/PR plumbing moves from roles-cmd.ts into manifest-edit.ts
so both commands share the single-repo worktree handling.

An e2e test drives add -> pull, update -> pull and remove -> pull through
the built CLI: after `remove`, a member that still has the project active
has its deployed skills, rules and agents reclaimed on the next pull.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 19:01:14 +08:00
Jiahe GengandClaude Opus 4.8 89ac24a3d4 fix(votes): collect upvote adoption from tool-use evidence + opt-in LLM-judge (#723) (#744)
* fix(votes): collect upvote adoption from tool-use evidence + opt-in LLM-judge (#723)

Fixes #723. upvoted_count was structurally near-zero because collecting an
upvote depended on the main agent voluntarily emitting the
<!-- teamai:referenced-doc-ids: [...] --> marker (~3.7% in the issue's data).
This collects adoption WITHOUT AI self-declaration and removes that mechanism
entirely.

Signals:
- Tool-use evidence (always on): a recalled doc is adopted when the MAIN agent
  opens its file (Read/Grep/Glob/Bash). Sidechain tool calls excluded; gated to
  the recalled set; full-path or >=2-segment suffix match (no bare-basename
  cross-attribution); relative `./x` normalized; Bash harvests FILE-OPERAND
  tokens only (grep patterns, option values, `#` comments and `>`/`>>`/`2>`
  redirection targets never credit; `-e/-f` frees the file operand); a FAILED
  tool_result (is_error) revokes its refs; Glob/Grep matched files are harvested
  from the reader RESULT (input path is often just a directory).
- Opt-in background LLM-judge (TEAMAI_UPVOTE_JUDGE=1, off by default): a detached
  Stop handler asks the local signed-in CLI whether the latest reply used each
  still-uncredited recalled doc, grounded in the doc's real content. Grounded-only
  (a candidate whose excerpt cannot be securely read is dropped, so a forged
  recall marker cannot earn an upvote from its id alone); fail-closed excerpt read
  (lstat + realpath + .md-in-trusted-root); trusted roots derive from
  learningsRoots + pendingLearningsDir; prompt fences excerpts/reply as untrusted
  data. Each recalled doc is judged at most once per session via a per-doc
  judged-record (crash-safe: recorded AFTER the CLI call, so a killed run retries;
  later turns still judge NEW docs) — no exclusive claim marker.

Scope attribution: recall labels each hit [project]/[user]; while a project is
active a doc recalled from the inherited USER scope is read-only and is NOT
upvoted into the project team (matches recall.ts's recalled_count scoping and the
documented rule). Recall regions from a reader tool_result (file content the agent
opened) are UNTRUSTED — parsed into throwaway sinks so a forged region can neither
manufacture a doc-id nor poison a real doc's scope/path; only assistant text,
non-reader results, toolUseResult.stdout and plain-string content are trusted.

Concurrency & idempotency:
- All vote mutators serialize on one cross-process file lock; the votes file is
  written atomically (temp+rename) so a killed detached judge cannot leave a torn
  file that loadUserVotes would read as empty. creditedDocIdsForSession reads the
  YAML directly (never loadUserVotes) so a v1 file is not auto-migrated by an
  unlocked read.
- Per-session dedup ledger lives inside the votes file under the same lock; its
  TTL is measured from the session's first-seen time (firstTs) so a long/resumed
  session cannot re-credit an already-adopted doc; TTL-pruned every Stop; local-
  only (never synced to the team repo via mergeDeltas).

Also: deterministic "[teamai] Adopted team knowledge this session: <ids>" summary
(once per session, tools that print the Stop payload); finalAssistantText joins
all text blocks of the final message and accumulates across records sharing a
message id; recall lock-exhaustion is logged honestly; removed the
referenced-doc-ids parser/nudge/stash and its rules text in builtin-rules.ts /
pull.ts. gitOnly and promote thresholds unchanged.

Docs: document TEAMAI_UPVOTE_JUDGE (usage-guide en+zh); note OpenCode does not
participate in adoption (session.idle carries no JSONL transcript_path);
git-native-memory design flow + both decision tables updated to adoption-driven.

* fix(votes): tighten adoption evidence in transcript parser (#723)

Address the #744 review's precision findings in adoption collection:

- Reader tool results no longer harvest every Markdown-looking string;
  only whole-line file paths and grep `path:line:` prefixes count, so an
  unrelated notes.md that merely mentions a recalled doc's name cannot
  credit it.
- Relative tool-call paths are resolved against the transcript entry's
  cwd before matching, so a relative `learnings/setup.md` opened in one
  checkout is not misattributed to a recalled doc under another checkout.
- Shell command splitting is quote-aware, so a `|` inside a quoted grep
  pattern no longer forges a synthetic `cat` segment that falsely credits
  a doc named only in the pattern.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(votes): dedup the LLM-judge via the vote ledger, drop session marker (#723)

The per-session "judged-docs" marker introduced crash-unsafe and
once-per-session-violating behavior (#744 review): a transient CLI
failure was recorded as judged and never retried, a positive verdict
was marked judged before the vote write so a busy lock lost it
permanently, an early negative verdict permanently excluded a doc a
later reply actually used, and the 24h marker TTL re-credited docs on
a resumed session.

Remove the marker entirely and rely on incrementUpvoted's atomic,
lock-protected per-session ledger, which already dedups credits across
the foreground and background passes. A verdict is now recorded only
after the atomic credit succeeds; an unadopted recalled doc may be
re-judged on a later Stop (the judge is opt-in), which is the accepted
cost of removing the crash-unsafe marker.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-09-24 18:53:02 +08:00
dvd233 9d3a91cf76 fix(push): honor explicit branch and protect dirty team clones (#690) 2026-09-24 18:43:14 +08:00
Yu Geigei 57afe76810 feat(models): merge show into list with an optional profile (#782)
Model catalogs are small, so `teamai models list` now prints every profile in full: API key source, gateway, models by protocol, compatible agents, and where it is active. `teamai models list <profile>` narrows the output to one profile, and the separate `show` command is removed.
2026-09-24 15:37:53 +08:00
Saul Moro 2ab697d062 fix(usage): discard pre-upgrade usage and stop falling back past an unreadable config (#748) (#758)
* fix(usage): discard pre-upgrade usage and stop falling back past an unreadable config (#748)

Follow-up to #753, from its review.

- resolveConfigForDir returns null when any project config was reported
  unreadable, even if a lower-priority one (a legacy .teamai/ behind a broken
  partition) loads: that one may name another team.
- The user scope's usage.jsonl is the old shared file. #753 only emptied it on
  a machine's first user-scope init, so a machine that already had a user
  scope reported every project's pre-upgrade usage to it. The first access
  after the upgrade now discards what an earlier release left there and
  writes ~/.teamai/usage-per-scope. One process discards, under acquireLock;
  concurrent hooks wait for the marker, so none deletes what another recorded.

* fix(review): parse the empty usage file in its test; scope the fallback wording to team hooks (#748)

- "handles empty file" wrote no marker, so the discard removed the file and
  the read passed on a missing file. A first read now settles the file as
  the scope's own, and the test asserts the file survives.
- The session-start pull still resolves its project on its own, so the
  "never falls back to a lower-priority config" rule is stated for team
  hooks and skill usage only (CHANGELOG, usage guide en/zh-CN).

* fix(usage): keep the user scope's usage in its own file, safe across a rollback (#748)

The usage-per-scope marker could not tell a pre-upgrade event from one an
earlier release appends after a rollback, so a reinstall reported those to
the user-scope team. The user scope now records in ~/.teamai/user-usage.jsonl,
which no earlier release writes; ~/.teamai/usage.jsonl is removed, never read.
Drops the marker, its lock and the bounded wait.

* fix(usage): a failed removal of the shared usage file does not stop the user scope (#748)

Also names the user scope's own file where comments and the design diagram
still described every scope's usage as <dataHome>/usage.jsonl.

* docs(changelog): drop the claim that teamai doctor reports an unreadable project config

resolveDoctorContext falls back past an unreadable project config the way
detection does, so doctor diagnoses the config it falls back to and says
nothing about the broken one (#752).

* fix(usage): leave the shared usage file in place instead of removing it on every access (#748)

getUsagePath deleted ~/.teamai/usage.jsonl on every user-scope call,
including each hook append and the read-only `teamai stats`. The user scope
never reads that file, which is what keeps its events off the team; the
delete added a side effect to a path getter and a failure path to guard.
2026-09-24 15:04:18 +08:00
RererrandClaude Fable 5.1 a2f93ae3d2 fix(config): release only Claude's MCP servers on a root move; read the recorded root in import and skill tracking (#775)
A re-init that moved the Claude Code root handed the full team config to
reconcileMcpForConfig({ removeAll }), which walks every MCP-capable tool,
so Codex, Cursor and the rest lost their teamai-managed servers until the
next pull. The release now narrows the team config to Claude.

import --from-claude scanned ~/.claude/rules and skill-use tracking only
knew the static ~/.claude/skills; both now resolve the recorded root. The
resolution (project config governing the directory, else user scope) moves
into resolveMemberToolRoots so the local agent, import and tracking agree;
tracking resolves it from the hook's reported directory. The helper checks
that the directory exists before probing, as resolveConfigForDir does, so a
hook from a deleted worktree still records — this also stops the local
agent from throwing on a missing workspace path.

Follow-up to #728 (third review pass, findings 1 and 5).

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 15:01:41 +08:00
Yu Geigei da13c1119b feat(models): share gateway model profiles across agents (#675)
Add `teamai models` to point Claude Code, Codex, OpenCode, CodeBuddy, and
WorkBuddy at a team or personal model gateway.

- A team publishes `models/models.yaml` (id, name, base_url, api_key
  placeholder, model_groups by protocol); each member keeps the API key
  locally or as an environment-variable reference.
- `models switch` updates every installed, compatible agent (or `--agent`),
  asks for a missing key once, and accepts `--model` for the default.
- `teamai pull` re-applies the team's latest catalog to agents already
  switched to it; agents never switched are left alone.
- TeamAI records the managed fields before its first switch, skips agents
  whose managed fields changed outside TeamAI, and `models restore` puts
  the originals back. Claude's `/model` pick is not treated as a takeover.
- Claude family aliases map to matching gateway models or the default;
  Buddy entries use `${VAR}` key references; Codex edits are parsed and
  verified before writing.
- Push rejects an invalid catalog; user-scope uninstall restores model
  settings first.
2026-09-24 11:45:54 +08:00
RererrandClaude Fable 5.1 55b71efb69 feat(config): honor a relocated Claude Code config dir via toolRoots (#728)
Claude Code can move its whole user config directory with
CLAUDE_CONFIG_DIR, but teamai resolved every Claude path from the
team-wide toolPaths (.claude/...), so hooks, skills and rules were
written to ~/.claude, which that Claude Code never reads, and doctor
stayed green.

Add a member-level `toolRoots` key to the local config. In user scope
`scopedToolPaths` re-roots every path of the listed tool; a new
`hookToolPaths` does the same for writes that land in HOME regardless
of scope (hook injection/removal/listing, doctor's hook checks, the
local agent). `teamai init` records CLAUDE_CONFIG_DIR into
`toolRoots.claude` and keeps it across a re-init; `teamai doctor`
reports when the variable and the effective root disagree.

An explicit CLAUDE_CONFIG_DIR=~/.claude is recorded too: Claude Code
then reads .claude.json from inside the directory, so the MCP companion
file moves inside the root even when the root is unchanged. Accepted
roots are one directory in HOME or .config/<name>, the shapes
`toolInstallRoot` can express; the hook gates in hooks.ts now use it so
hook and resource gates agree. Only `claude` is accepted for now: it is
the one tool whose every user-scope write goes through toolPaths.

Closes #725

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 11:20:01 +08:00
dvd233 5576b38db7 fix(init): preserve additional roles selected at the prompt (#765) 2026-09-24 10:47:10 +08:00
Saul Moro 72305c68b8 fix(skills): one share gate, actionable refusals, and a louder stub deploy (#747)
* fix(skills): one share gate, actionable refusals, and a louder stub deploy

Follow-ups from the review of #699:

- The Stop-hook reminder and `teamai skill get share` ask one gate
  (`shareGate`, through `contributeHintAllowed`). The hook skipped the
  unreadable-project-config check, and the legacy `teamai contribute-check`
  command, still called by hooks written before the dispatcher, checked
  nothing, so both nudged towards a command that refused.
- The gate reads only a config load failure as "cannot be loaded"; any other
  fault propagates (the hook withholds the reminder and logs it at debug).
- A `config` refusal says what failed (the file and position for a parse
  error) instead of pointing at `teamai doctor`, which cannot see a broken
  config. `skill show` now refuses through the same helper, so its hint moves
  from stdout to stderr like `skill get` and `skill path`.
- `pull` warns when the discovery stub cannot be deployed (it was an empty
  catch on the fast path and a debug line on a full sync), and so does the
  legacy prune.
- Error text no longer claims a reason was logged when none was: an empty
  config is named as empty, and `init` points at ~/.teamai/debug.log, where
  every path that deploys nothing now records why.
- `core` routes a bare `/teamai` right after a friction reminder to `share`,
  as the stub already said.
- The command drift guard rejects an unknown subcommand inside a group
  (`teamai skill gett core` passed before).
- The contribute-check e2e asserts the reminder's real text again; the usage
  guides (EN, zh-CN) and the design doc cover the config refusal, the gate and
  the reminder routing.

* test(learnings): retry temp-dir cleanup that races a detached git gc

A push into the bare origin can leave `git gc --auto` writing to
objects/pack after the test returns; the single rmdir in afterEach then
fails with ENOTEMPTY (seen on CI, Node 22 ubuntu, #747).

* fix(skills): gate skill show before its lookups, name the failing field

Review of #747:

- `skill show share` under a broken project config searched the user
  config's team repo and agents, which detection falls back to, and printed
  a `share` found there. It now asks the gate first and refuses on a config
  block before any lookup. With an empty user config it refuses instead of
  ending in a stack trace.
- A config that parses but fails validation reported the Zod JSON dump,
  whose first line is `[`, so the refusal said `config.yaml: [.`. Every
  config loader now reports each issue as `field: reason` on one line.
- The docs and skills that describe the share reminder or the refusal say
  it is withheld on a read-only source and while the config cannot be
  loaded, and that a validation failure names the field: product-overview
  and usage-guide (EN, zh-CN), designs/skill-serving.md, core/SKILL.md,
  contribute-member, setup-admin, join-member and manage-admin.

* fix(skills): no share reminder where teamai is not set up

`contributeHintAllowed` fell open with no config at all, so a caller other
than the dispatcher (the legacy `teamai contribute-check`) still nudged in
projects that never set up teamai, which have no team to share with
(#748). It now returns false there. Serving the skill stays fail-open.

* fix(contribute-check): gate the legacy reminder on the session's cwd

`teamai contribute-check --stdin` asked the share gate about the directory
the hook process started in, while the session analysis used the payload
cwd. Started outside the project, it could read the user config and nudge
where `teamai skill get share` refuses (a project config that does not
load). It now moves to the payload cwd first, as hook-dispatch does.

* fix(pull): keep a debug.log record when the stub cannot be deployed

The previous commit turned both deploy catches into `log.warn`, which is
muted in silent mode and never reaches debug.log, and a SessionStart pull
runs detached with its output discarded. So the automatic pull, the one
that deploys the stub for most members, lost the only persistent record
it had. Both catches now warn and write the same line to debug.log.

* fix(skills): skill show and list never answer for the fallback team

Known issues left by #747:

- `skill show <name>` and `skill list` on a config that exists but does
  not load ended in a Node stack trace, and under a broken project config
  they searched the user config detection falls back to: another team's
  repo and agents. Both now ask `detectTeam`, the one place that tells
  "this team", "no team" and "cannot tell, and why" apart (`shareGate` is
  built on it). Without a usable team, `show` answers from the package
  alone and `list` prints only the packaged catalog; both say what failed
  on stderr and exit 1.
- A teamai.yaml that exists but fails validation was reported as "not
  found. Check your repo path". It is now named as invalid, empty or
  unreadable, like the local config.

* fix(skills): the gate reads the session's directory, and no project config is skipped

Codex review of 5793758:

- A project-location config that is not `scope: project` (or omits
  `scope`, which defaults to user) was skipped without a word, so the gate
  read past it to the user config. It is now reported as unusable, unless
  it is the user config itself, as when running from HOME.
- The legacy `contribute-check` changed into the payload cwd and, if that
  failed, asked the gate about the directory the process started in. It
  now passes the payload cwd to the gate (`detectTeam(cwd)`), and a cwd
  that no longer exists holds no project config, so only the user config
  is asked, as #753 does.

* fix(logger): record warnings in debug.log

`log.warn` wrote to the console only and was muted in silent mode, so a
detached SessionStart pull, whose output is discarded, lost every warning:
the stub deploy failure and the legacy prune among them. Warnings now reach
debug.log like debug and error lines. `warnStubNotDeployed` drops the
second `log.debug` call, which printed the line twice under --verbose.

* fix(skills): the dispatcher gate reads the payload cwd; a symlink is not HOME

Codex review of b0583f5:

- The dispatcher's `contribute-check` and `pending-hint` handlers asked
  the gate about the process's directory, trusting hook-dispatch's
  `chdir`; when that failed, the launcher's config decided. They now pass
  `resolveHookCwd(stdin)`, as the legacy command does.
- The HOME exception for a non-project scope compared the config file's
  real path, so a project config symlinked to ~/.teamai/config.yaml passed
  for the user config. It is now decided by the project's location: its
  root is HOME.

* fix(skills): only a missing cwd falls back to the user config; load it once

Codex review of 15a5b5d:

- `detectTeam` read any failure to see the payload cwd as "deleted", so a
  cwd it could not open (no permission, a path through a file) fell back
  to the user config and could allow the reminder. Only ENOENT does now;
  anything else is `unusable` and withholds it.
- `skill show share` and `skill list` loaded the config twice, through the
  gate and then the team lookup, and reported a broken one twice. Both
  detect the team once and hand it to the gate.

* fix(logger): a file-only record instead of persisting every warning

b0583f5 made every `log.warn` append to debug.log, wider than the two
failures it was for, and it wrote unrelated subprocess errors to disk.
`log.warn` is console-only again; `log.persist` writes one line to
debug.log and never to the console. The stub deploy catches and the
legacy prune catch use both, so a detached SessionStart pull keeps the
record and --verbose prints it once.
2026-09-23 22:47:00 +08:00
Saul Moro 5502d8ec10 fix: keep TeamAI out of projects that never set it up (#748) (#753)
* fix(hooks): run team hooks only where TeamAI is set up (#748)

Hooks of a project-scope install live in HOME, so they fire in every
project on the machine. With no config for the hook's cwd they ran anyway:
the Stop share nudge (even with recall off), the TodoWrite recall nudge,
and local capture of sessions and skill usage that another project's
report later pushed to its team.

Handlers that need a team now declare requiresConfig; the dispatcher drops
them when neither a project nor a user config resolves. Only machine-level
work runs there: update check, session-start pull, local agent, package
pending hint. The legacy track paths skip recording the same way.

* fix(stats): keep skill usage in the scope that recorded it (#748)

Every scope appended to one ~/.teamai/usage.jsonl, so whichever project
pulled next reported every project's skills to its own team.

Usage now goes to <dataHome>/usage.jsonl of the scope that resolves for
the session's directory (detectProjectConfig(cwd) ?? loadLocalConfig(),
as the dispatcher does). Each report reads and truncates only its own
file; teamai stats shows the current scope. A machine's first user scope
starts with an empty file: what it held cannot be attributed.

* fix(review): one scope resolver for hooks, usage and stats (#748)

- resolveConfigForDir (config.ts) is the single resolution the dispatcher,
  the usage writers and readers, and teamai stats use. A host that sends no
  cwd (OpenClaw) resolves from the process cwd, and an unreadable project
  config yields null instead of falling back to the user scope.
- readUsageEvents / truncateUsageAfterReport require a scope; no path reads
  the old shared file by default. readKnownSkills reads its scope's file.
- Real-dispatch tests: no-config session leaves no trace, cwd-less host,
  unreadable project config.
- Docs: machine-level handler list, data-directory-layout note.

* fix(review): scope wording in CHANGELOG and readKnownSkills (#748)

* fix(review): gate legacy contribute-check and tolerate a missing cwd (#748)

The hidden 'teamai contribute-check' command, still called by hooks of
older installs, had no config gate, so it nudged in projects without
teamai. It now resolves the scope like the dispatcher and skips when
none resolves.

resolveConfigForDir no longer throws for a directory that does not
exist (simple-git refuses it); a hook naming a deleted worktree falls
back to the user scope.
2026-09-23 20:36:07 +08:00
Saul Moro 95cea46182 fix(manifest): reject namespace strings that are not safe path segments (#710)
* fix(manifest): reject namespace strings that are not safe path segments

A resource namespace becomes a directory component (skills/<ns>/,
agents/<ns>/, learnings/<ns>/) exactly as a project id does, but only the
project id was refined. Both manifests accepted a namespace like
'../../evil', and roles.yaml had the same hole.

Guarded at the manifest boundary, which is where projects.ts already claims
it is enforced and the only place these strings enter the process. The
existing isSafeNamespaceSegment guards in contribute.ts and
resources/agents.ts stay as defence in depth.

The doc comment pointed at the wrong layer: an id read from a hand-edited
config.yaml resolves through getProjectOrThrow, so it can only ever name a
project the manifest already validated. Corrected to say so.

No fixture or e2e manifest in the repo ships a namespace containing '/' or
'..', so nothing that parses today stops parsing.

* docs(changelog): note the manifest namespace guard

* fix(manifest): guard namespaces against traversal only, and say what is wrong

Review findings on #710.

The first cut reused SAFE_ID (^[A-Za-z0-9._-]+$) for resource namespaces. That
allowlist is right for a project id, which is also typed on the command line and
split on commas, but for a namespace it rejects far more than traversal: a team
whose skills live under a non-ASCII directory, or one with a space in the name,
would have stopped parsing although the directory is perfectly safe. The
namespace guard now tests what actually matters -- no path separator, no `:`
(drive-relative on Windows), no control character, and not `.` or `..` -- while
the project id keeps its narrower spelling.

Both live in src/manifest-schema.ts, which is what roles.yaml and projects.yaml
genuinely share; roles.ts no longer reaches into projects.ts for the schema.

Running the CLI against a manifest with `../../evil` showed the second half: the
zod failure escaped as a raw ZodError, so `teamai pull` printed a validation
object instead of a sentence. parseManifest now reports it the way the
hand-written checks beside it do, naming the entry:

  Invalid projects manifest: projects.0.resources.skills.1: resource namespace
  must be a single path segment (no '/', '\', ':' or control characters, and
  not '.' or '..')

Docs: the namespace rule is stated where each manifest is documented, in both
usage guides and in the multi-project design doc.

* fix(manifest): reject DEL and C1 controls in a namespace too

Review P2 on #710: the guard rejected only U+0000-U+001F while the error
message and the docs promise every control character, so U+007F and the
C1 range U+0080-U+009F still parsed. Range extended and the three ranges
covered in the projects and roles fixtures.

* fix(manifest): reject the Win32 dot/space aliases of . and ..

Review P1 on #710: the guard tested for the exact strings '.' and '..',
so '.. ', '.. .' and '...' passed. Win32 strips trailing spaces and
periods from a path component, so each of those reaches the filesystem
as '..' and escapes the namespace directory it was supposed to name.

A segment of nothing but dots and spaces is '.' or '..' in disguise and
is refused as such; 'a..' keeps parsing, since it stays inside its
parent. The project id, whose allowlist already excluded spaces, refuses
any run of dots for the same reason.

* fix(manifest): keep the project id rule untouched, scope the role docs

Review on #710.

The dot/space fix reached further than it needed to: tightening the id
to reject every run of dots also rejected '...', a working POSIX
directory name the id rule has always accepted, so a manifest that
parses today would have stopped. The id is back to the exact '.'/'..'
check it had before this PR, with a test that says so. Only the
namespace rule moves.

The role docs claimed every namespace under resources: follows the rule,
but roles.yaml's learnings: is accepted for backward compatibility and
ignored at runtime -- it names no directory, so holding an old manifest
to the rule would reject it over a field nothing reads. Both usage
guides and the design doc now name the fields that do take effect.

* docs(manifest): state the id and namespace rules separately

Review P2 on #710: after the id was left on its old rule, the docs still
described one rule for both, so they claimed a project id rejects any
name made only of dots and spaces while '...' parses. Each rule now
stands on its own in both usage guides and the design doc, and the
projects.ts comment says why the id is not held to the namespace rule.

* fix(manifest): reject a namespace with a trailing '.' or space

Review P1 on #710: refusing only names made entirely of dots and spaces
left the aliasing half open. Win32 strips trailing periods and spaces
from every path component, so 'frontend.', 'frontend ' and 'frontend..'
all resolve to 'frontend' -- one namespace reading and writing another's
directory, which is the isolation a namespace exists to provide.

The rule is now the trailing character itself, which covers the escape
('.. ' arriving as '..') and the aliasing in one test, and '.' and '..'
fall out of it. A dot inside a name ('alpha.v2') is untouched.

* fix(pull): a roles manifest that does not parse must not widen delivery

Review P1 on #710. resolveResourceNamespaces caught every failure from
loadRolesManifest and carried on with no role filter, which for a member
with no active project means an unfiltered sync: making the schema
stricter would have turned 'skills: [../../evil]' into 'deliver every
namespace', the opposite of what the guard is for.

The catch was covering two cases at once, because loadRolesManifest
throws both when the file is absent and when it is invalid. Only the
first is the legacy, unfiltered case, so it now throws a typed
RolesManifestMissingError and the catch reacts to that alone. An invalid
manifest propagates and pull fails the scope with the entry named --
exactly what an invalid projects manifest already does.

Verified against the real CLI: with 'skills: [evil/nested]' pushed to the
team repo, pull reports the failed 'Skills to deliver can be resolved'
check and the three delivered skills are left untouched; restoring the
manifest syncs them again.

* fix(manifest): narrow 'absent' to ENOENT, refuse Windows device names

Review on #710, two of the three findings; the third was a stale read of
the PR description, which the e2e section had already been rewritten to
match and which is now updated before the push rather than after.

readFileSafe returns null for every read failure and for an empty file,
so an unreadable roles.yaml was indistinguishable from one that was never
written -- and 'never written' is the one case allowed to relax role
filtering. projects.yaml had the same hole, where a null manifest means
'this team is not partitioned'. Both loaders now read the file directly:
ENOENT is absence, and a permission error, a directory or an empty file
is an error that fails the pull.

Windows opens a device for CON, NUL, AUX, PRN, COM0-9 and LPT0-9 in every
directory, extension or not, so a namespace spelled that way cannot be
the directory the manifest names. A name that merely starts like one
(console, community) is untouched, and the project id stays out of this
rule as it stays out of the others: it is a working POSIX name the id
rule has always accepted.

* fix(manifest): narrow every roles fallback, drop COM0/LPT0 from the device set

Review on #710.

The fail-closed change covered resolveResourceNamespaces but not the
other callers that fall back when the loader throws, so a malformed
manifest still reached an unfiltered sync by another route: bootstrap.ts
left the member role-less while auto-selecting the sole role,
resources/skills.ts and push.ts guessed the namespaces from the role ids,
and config.ts skipped the legacy migration and left the role unset. Each
now reacts to RolesManifestMissingError alone. roles-cmd.ts keeps its
broad catches on purpose: those commands report the error to the person
running them instead of deciding what to deliver.

Windows reserves COM1-COM9 and LPT1-LPT9, not COM0/LPT0, so the guard was
rejecting two ordinary directory names for no safety gain. Both are now
covered by the test that pins 'console' and 'community' as valid.

* fix(manifest): prove absence before trusting it, add the superscript devices

Review on #710.

ENOENT is not proof that a manifest is absent: a committed symlink whose
target is missing reads exactly the same way, and absence is the one
answer that lets a caller relax its filtering. The path is now lstat-ed
before absence is believed, so a dangling link is an error like any other
unreadable file.

Windows reads the superscript forms of 1, 2 and 3 as device numbers, so
COM and LPT followed by one of those join the ASCII-digit set.

The third finding, that resolveResourceNamespaces returns before reading
roles.yaml, is not a fail-open and is left as it is: that branch is
reached only when the member has no role, and a role-less member gets the
same unfiltered sync from a perfectly valid manifest, since every role
namespace below is gated on primaryRole. Reading the manifest there would
only add a new way for their pull to fail. The reasoning now sits in the
code beside the early return.

* fix(init): a broken roles manifest must stop init, a skipped prompt must not

Review on #710.

Both init paths swallowed every role-selection failure and carried on
without a role. A role-less config matches every role when hooks are
reconciled, so a manifest that does not parse installed exactly the hooks
it restricts.

Narrowing the catch to RolesManifestMissingError alone was too much: the
same block also absorbs a person skipping the role prompt, and a
non-interactive run reaches it, so init would have started failing for
anyone who does not pick a role. That case is now its own type,
NoRoleSelectedError, and the two lenient cases are named while a parse
failure or an unknown --role propagates. Both catch blocks read the same.

Also: ENOENT proves nothing about absence when the DIRECTORY is a
dangling link -- readFile and lstat on the file both report ENOENT -- so
the path's components are walked, and the first link that leads nowhere
is reported instead of being read as 'no manifest'.

Verified in init.test.ts (malformed aborts and writes nothing, absent
still initializes role-less) and against the real CLI in single-repo
mode: no manifest exits 0 with the role unset, '../../evil' exits 1, and
a valid manifest with --role sets primaryRole: frontend.

* chore(ci): re-run review against the rebased head

No code change. The Codex review workflow re-reviews on push, and the
PR body now carries the real-CLI matrix run on the rebased head.

* fix(manifest): expand '~' when reading a manifest, guard role ids used as fallback namespaces

Review findings on #710 after the rebase.

readManifestFile replaced readFileSafe/readFileIfExists, which expanded a
home-relative repo.localPath. Without the expansion a documented
`~/.teamai/...` path is searched under the current directory, read as
absent, and roles.yaml absence relaxes the filtering. The path is expanded
before both the read and the dangling-link walk.

When roles.yaml is absent, skills.ts and push.ts fall back to the role ids
as namespaces. A role id is an unrestricted string, so a value such as
'../../outside' reached path.join, and SkillsHandler.removeItem could
recurse outside the team repo. Both fallbacks now pass the ids through the
namespace guard and fail with the rule's message.

* fix(config): expand '~' in repo.localPath at the config boundary

A home-relative repo.localPath reached simple-git, the manifest readers and
every resource path unexpanded, so `teamai pull` failed with
'Cannot use simple-git on a directory that does not exist'. The schema now
expands it once, at parse time, so no consumer has to. expandHome moves to
utils/home.ts (fs.ts re-exports it) so types.ts can import it without
pulling in the fs helpers.

* fix(manifest): reject the CONIN$ and CONOUT$ console devices too

Review finding on #710. Windows opens the console for these names in any
directory, extension or not, the way it does for CON, so a namespace spelled
that way cannot be the directory the manifest means.

* fix(push): guard the role id silent mode uses as a namespace

Review finding on #710. With a valid manifest that maps the role to several
skill namespaces, silent push assigned primaryRole as the namespace without
the check the fallback path already has. It now goes through the same
guard, so 'frontend.' or 'CON' fail the push instead of becoming a path.

* fix(manifest): reject namespaces that differ only by case, classify the guard as breaking

Review findings on #710. Two namespaces of one resource type that differ
only by case (or Unicode normalization) name a single directory on the
default Windows and macOS filesystems, so a role scoped to 'frontend' would
read 'Frontend' too. Each manifest is checked when it loads; the pull path
checks roles.yaml against projects.yaml as well, since both share skills/,
knowledge/ and agents/.

The namespace guard makes a manifest that parsed before fail every pull, so
the changelog entry moves under Breaking Changes.

* fix(pull): check roles.yaml against projects.yaml for role-less members too

Review finding on #710. The cross-manifest case-alias check ran only when
the member had a role, so a project-only member pulling skills/Common with a
role's skills/common in the same repo was not stopped. roles.yaml is now read
whenever a projects manifest is in play; an absent one stays absent, a broken
one fails the pull as it does for a member with a role.

* fix(manifest): fold case the way filesystems do when comparing namespaces

Review finding on #710. The alias key was normalize('NFC').toLowerCase(),
which is not case folding: 'σ'/'ς' and 's'/'ſ' stayed distinct although
case-insensitive filesystems give each pair one directory. The key now
upper- then lowercases each code point on its own, which folds both pairs
and sidesteps the context-sensitive final-sigma rule. It errs toward
joining ('ß'/'ss', 'ı'/'i'), which can only reject a pair.

* fix(config): keep the config loadable when the roles manifest is broken

Review finding on #710. migrateLegacyRoleConfig rethrew a manifest parse
error, which loadLocalConfig caught and turned into null, so every command
reported "teamai is not initialized" — pull included, leaving the member no
way to fetch the fixed manifest. The migration now skips with a warning and
returns the config unmigrated.

That alone would widen delivery: a role-less member who would have been
migrated to 'hai' reached resolveResourceNamespaces' unfiltered early return
without roles.yaml being read. roles.yaml is now read for every member before
that return, so a broken one fails the pull (absent still means unfiltered).

* fix(status): report a resource type it cannot scan instead of crashing

Found running the real CLI on #710. scanLocalForPush resolves namespaces
through the roles manifest (agents via resolveResourceNamespaces, skills
when it falls back to role ids), and a manifest that does not parse now
throws there instead of being read as "no filter". status let that escape
as a stack trace after printing half its report. Status is where a member
looks to find out why pull failed, so it now warns with the error for that
type and lists the rest, as it already does for git status.

* fix(status): do not report "(none)" when a resource type could not be scanned

Review finding on #710. With every successful scan empty and one type
failing, status printed the warning and then "(none)", which reads as a
complete clean result. It now says "(none in the types that could be
scanned)" in that case.

* fix(config): a role the manifest could not resolve matches no role-scoped entry

Review finding on #710. When the legacy role migration cannot read the
roles manifest, the config stayed plainly role-less, and resolveMembership
reads role-less as "every role": hooks, MCP servers and env variables scoped
to roles reached a member the manifest would have made 'hai'. The pull
refused the manifest for skills, but those reconcilers still ran.

The migration now marks the in-memory config roleUnresolved, a runtime-only
field like dataHome that serializeLocalConfig drops and the schema strips on
load. activeRoleIds returns [] for it, so role-scoped entries reach nobody,
unscoped ones apply as before, and the reconcilers remove role-scoped entries
already installed. The next load decides the role again.
2026-09-23 19:22:54 +08:00
dayanandClaude Sonnet 5 9d7e50bb50 feat(pi): add Pi Coding Agent integration (#692)
* feat(pi): add Pi Coding Agent integration

Squash-rebased onto the latest upstream/main to resolve the PR's merge
conflict (main gained #693/#685/#694/#691/#681/#680/#666 since this branch
forked). This combines all commits from the PR into one, applied cleanly on
top of the new base — no functional changes from the previously reviewed
state.

The only real conflict was in src/__tests__/uninstall.test.ts, where diff3
split a test mid-body because of the repeated `});` boilerplate around it;
resolved by keeping both sides' new tests intact, in full.

* fix(pi): gate agent-hook files on the same per-slug marker ownership check

applyPiAgentHook()/removePiAgentHook() wrote and deleted teamai-agent-<slug>.ts
purely by path, with no ownership check — the same class of bug already
fixed for the main teamai-hooks.ts file, but never extended to the per-slug
HTTP agent-hook files. A user-authored file at that conventional path could
be silently overwritten on sync or deleted on uninstall.

Adds hasPiAgentHook(slug), mirroring hasPiHooks: injection now skips (with a
warning) instead of overwriting a same-named file without the
`[teamai] agent hook [<slug>]` marker, and removal skips instead of
deleting one. uninstall.ts's discovery scan now derives each file's slug and
checks the same marker before scheduling it for removal, instead of
matching by filename prefix alone.

* fix(pi): fail install_hook_rule instead of silently acking a skipped Pi agent hook

applyPiAgentHook warned and returned normally when the requested event has no
Pi equivalent or a same-named extension file exists without the TeamAI
marker. The caller in local-agent.ts wrote the manifest entry and acked
success regardless, so the server and local state believed the hook was
installed even though the file was never touched. Throw in both cases so the
existing install_hook_rule error path acks failure instead.

Also document the known limitation (shared with the OMP adapter) that a
scoped Pi uninstall is not durable across multiple projects on the same
machine, since the extension is one machine-wide file and hook dispatch has
no per-project exclusion check.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 16:22:31 +08:00
Saul Moro ca6e51251f feat(skill): serve builtin skill content from the CLI, deploy a discovery stub (#699)
* feat(skill): serve packaged skill content from the CLI

Add `teamai skill get <names...> [--full] [--all]` and `teamai skill path
[name]`, so an agent can read built-in skill content that always matches the
installed CLI version instead of a copy deployed into its skills directory.

`get` prints SKILL.md byte for byte, frontmatter included, with {SKILL_DIR}
resolved to the absolute packaged directory so documented script invocations
run as-is. `--full` appends references/ and templates/, walked recursively and
sorted by relative path, because our references nest one level deeper than the
flat layout agent-browser assumes.

Content goes to stdout and every diagnostic to stderr, so the output stays
byte-exact when piped. An unknown flag warns and continues; an unknown name is
fatal, since acting on the wrong skill is worse than a retry.

`skill list` gains the served catalog and `--json`; `skill show` resolves
packaged skills before the installed-agent fallback, which is what keeps it
working once the deployed unit becomes a stub. Legacy directory names resolve
as aliases.

Refs #678

* refactor(skills): move content to skill-data and deploy a single stub

Agents now receive one file: `skills/teamai/SKILL.md`, a discovery stub of
about 2 KB whose description carries the triggers of every workflow and whose
body holds the commands that load them. The workflow content moves to
skill-data/{core,share,wiki}, which is never deployed and is printed by
`teamai skill get`.

Before this, `deployBuiltinSkills` copied three whole trees — 176 KB — into
every installed agent on every pull, so the text an agent read could disagree
with the CLI it documented until the member ran a pull, and a machine with ten
agents held ten copies. skills/ keeps its meaning ("everything here is
deployed"), which is what lets BUILTIN_SKILL_NAMES collapse to one name.

The stub is copied verbatim: no ensureSkillFrontmatter on the way out, so a
deployed copy that differs from the packaged one is a bug rather than a
variant. Recall no longer gates deployment, since the stub routes to every
workflow; the run-time gate for share lands with the pruning pass.

Uninstall learns the legacy directory names, which it would otherwise leave
behind on every machine that upgraded.

"skill-data" is added to package.json files, with a test that asserts it
through `npm pack`: without that entry every test still passes against the
repo and `skill get` serves nothing once installed from the registry.

Refs #678

* fix(skills): repair stale commands, broken refs and frontmatter

An audit of the three builtin skills found 60 defects. This fixes the ones that
survive the move to skill-data, and splits the two skills that were carrying
more than one job.

Stale CLI surface. The wiki skill advertised `teamai extract graph`, a command
that has never existed. The hand-written "ground truth" cheat sheet in the
teamai skill omitted 19 real commands while telling the agent that anything
missing from it could be checked with `--help` — which fails for the flags
`--help` hides. The cheat sheet is replaced by
`skill-data/core/references/commands.md`, rendered from the CLI's own command
table, with hidden flags marked as such. Two tests guard it: one regenerates
the file and diffs, the other resolves every `teamai …` string written anywhere
in skill-data against the command table and fails on an unknown command or
flag. That second test is the one that would have caught e151d43, 1ca43ac,
8bb0548 and 2ddb546 before they shipped; it carries a case proving it catches
`teamai extract graph`.

Paths. Everything the skills told an agent to read or execute assumed the skill
sat in the agent's own directory: `python3 scripts/scan_repo.py` from a cwd that
is the target repo, references cited by bare filename in two different
conventions, methodology paths handed to sub-agents inside input packets. All of
them now go through {SKILL_DIR}, which `skill get` resolves. The README template
nobody referenced is wired into the step that writes the knowledge-base README.

Frontmatter. None of the three skills declared allowed-tools, so the first
command of every flow hit a permission prompt. The wiki skill kept its trigger
words and prerequisites inside the description text; both move into the body.

Splits. `core` keeps what a daily user needs and `setup` takes day 0 and the
repo lifecycle, so the common path no longer carries ~500 lines of repo
creation. The wiki skill's phase procedures move into references/phases/, taking
its SKILL.md from 38.7 KB — larger than agent-browser's entire core — to 17 KB
with an index that says when to load each phase.

One contradiction is resolved in the author's text: the share skill mandated
that every generated document be written in Chinese, against global rule 1
("reply in the user's language") and this repo's own English rule. It now
follows rule 1.

Refs #678

* feat(pull): prune legacy builtin skill directories, gate recall at run time

Upgrading the CLI used to leave the pre-stub trees in place: cleanup skips
builtin names, and nothing else knew about them, so `team-wiki-codebase` and
`teamai-share-learnings` would sit in every agent directory on the machine
forever. Deployment now removes them first, in both the configured skills path
and Codex's shared `.agents/skills`. Unconditional, because those trees were
overwritten on every pull, so no local edit ever survived in them.

Recall moves from deploy time to run time. Before, `skipRecall` decided whether
the share skill reached the agent at all; with one stub routing to everything,
there is no directory to withhold, so `teamai skill get share` checks instead
and says what to enable. `--all` is exempt: an inventory dump is not an attempt
to run the workflow. With no team config to consult the gate fails open — a
fresh machine reading the docs gets the content rather than a refusal it cannot
act on.

deployBuiltinSkills drops its `skipRecall` option rather than keeping one that
no longer decides anything, and recall-toggle stops deleting a skill directory
it no longer owns.

Refs #678

* docs: align the nudge and the guides with CLI-served skills

`/teamai-share-learnings` was never a slash command of its own — it existed
because the directory was installed. The Stop-hook nudge now names `/teamai` and
carries `teamai skill get share` literally, so an agent can act on it without
having to infer the intent from the conversation. The five READMEs and both
usage guides follow.

Both guides gain the `skill get` / `skill path` commands and a short section on
why built-in skills are served rather than copied. `docs/designs/skill-serving.md`
records the contracts that are easy to break later: byte-for-byte output,
{SKILL_DIR} substitution, stdout/stderr discipline, recursive `--full`, the
run-time recall gate, the three drift guards, and when to retire
LEGACY_BUILTIN_SKILL_NAMES and the long-name aliases.

AGENTS.md and CLAUDE.md gain the rule that keeps this from rotting: skill-data
is treated like documentation, a behaviour change updates the affected skill,
commands.md is regenerated rather than edited, and new workflows go under
skill-data instead of into the stub.

Refs #678

* fix(skills): apply standards review findings

`teamai init` printed "Built-in skills (e.g. team-wiki-codebase) are ready to
use in your IDE now" seconds after deployment deleted that very directory. The
message now names the teamai skill and how it loads its workflows. Two comments
carrying the same stale name follow.

The five READMEs said different things: only the English one named the share
workflow and its command. All five now do.

`collectSupplementaryFiles` hand-rolled a recursive walk that
`listFilesRecursive` already does, including the ignore list that skips `.pyc`
and `__pycache__` next to the wiki's Python scripts. It calls the helper
instead. `listServableSkills` drops its fallback to `skills/`: a package without
`skill-data/` is broken, and serving the stub as if it were the content hides
that from the one error message built to report it.

Tests drop six non-null assertions for a helper that throws, per the repo's rule
against moving a compile-time error to run time.

AGENTS.md and CLAUDE.md record the exemption the branch created: skill content
printed by `skill get` keeps the language its author wrote it in, while the
command's own prompts, errors and listings stay English.

Refs #678

* fix(skills): apply spec review findings

Upgrading left the old references in place. Releases before the stub deployed
`skills/teamai/` with six reference files beside SKILL.md, and `teamai` is not a
legacy name to prune, so copying one file over that directory kept ~39 KB of
pre-stub instructions next to the new stub for good. Deployment now clears
everything the deployed unit does not contain before writing it, and a test
seeds the old layout to prove it.

Pruning reached neither reporting-only teams nor the Codex shared directory in
any test. The prune now runs before the reporting-only return, so a team that
switched to reporting-only still loses the stale trees, and the Codex
`.agents/skills` path is covered by a test. Excluded agents stay untouched, as
the enabledAgents whitelist documents.

The served content still routed to skills that no longer exist: five mentions of
`teamai-share-learnings` and one `/team-wiki-codebase --update`, which is the
rule this branch itself added being broken on arrival. One second-hop path
inside a sub-agent input packet was still relative.

The share skill's document template, frontmatter table and tag taxonomy move to
`references/doc-template.md`, taking the always-read body from 3 701 to 2 471
bytes. Two tests now assert what nothing guarded: every served skill's
frontmatter name matches its directory and declares allowed-tools.

A new e2e file runs the built CLI the way an agent does: every listed skill is
servable and byte-identical bar the resolved placeholder, the wiki scripts run
from the directory `skill path` prints, an unknown name exits 1 with empty
stdout, a hallucinated flag warns and still serves, and `--full` appends the
nested references in sorted order.

Refs #678

* fix(skills): prune only directories the CLI owned, gate every content path on recall

- LEGACY_BUILTIN_SKILL_NAMES drops teamai-workflow and teamai-import: they were
  reserved in the old guard set but never packaged, so a directory by either
  name is the user's own skill. Test: user-created skills with those names
  survive pull.
- The recall gate now covers skill get --all (blocked skill skipped, named on
  stderr), skill path (refused) and skill list --json (blockedByRecall, path
  null). skill list reads the flag from the catalog instead of re-checking.
- skill get [names...]: the positional is optional so --all is reachable from
  the real CLI; Commander used to fail with 'missing required argument'.
  Covered by the skill-serving e2e.
- commands-reference renders Commander's variadic marker (<names...>); the
  snapshot is regenerated.

* test(skills): drive the recall gate through the real CLI, guard the stub description budget

- skill-serving e2e: a HOME with a team whose recall is off; skill get share,
  --all, skill path share and skill list --json each withhold share, and all
  serve it after recall enable. The earlier HOME has no team config and fails
  open, so the gate was never exercised through dist/index.js.
- skill-content test: the stub description stays within 1024 characters.
- skill-commands-exist also scans the deployed stub.
- Docs and PR lead with content versioned with the CLI; the size numbers are
  measured (stub description 0.8 KB, body 1.3 KB; --full 32/36/115 KB).
- Content audit against origin/main: every file has a counterpart. Fixes:
  {SKILL_DIR} defined in core/setup/share where the references are listed, the
  wiki overview draws the served layout, team-wiki-codebase kept as a trigger
  word in the stub description.

* fix(skills): gate skill show on recall, prune Codex's shared dir only from Codex

Review follow-up on #699.

- `skill show <served skill>` refuses a recall-blocked skill with the same
  message and exit code as `skill get` / `skill path`; it printed the
  directory those two withhold.
- A skill resolved from skill-data/ is classified `[builtin]` directly.
  BUILTIN_SKILL_NAMES only knows the deployed stub, so `skill show core`
  reported `[local-only]` beside a package path.
- pruneLegacyBuiltinSkills reaches `.agents/skills` only on Codex's own
  pass. Another enabled tool's pass deleted Codex's legacy copies while
  Codex was excluded, against the enabledAgents guarantee.
- The share skill and its references are written in English; the generated
  document still follows the session's language. The AGENTS.md exception
  for Chinese skill-data output is dropped.

* fix(skills): one resolver for served skills, legacy names kept out of push, wiki in English

Review follow-up on #699.

- resolveServableSkill is the only way to obtain a PackagedSkill outside
  skill-content.ts; it returns `blocked` instead of the skill, so `get`,
  `path`, `list` and `show` inherit the recall gate by construction.
- push never offers `team-wiki-codebase` / `teamai-share-learnings` as new
  user skills: between the upgrade and the first pull they are still on
  disk (isCliOwnedSkillName).
- `recall disable` removes the legacy `teamai-share-learnings` directory
  again (LEGACY_RECALL_SKILL_NAMES), skipping excluded agents.
- `skill list` prints the packaged catalog before `teamai init`, with a
  hint for the team half, instead of failing on the team listing.
- skill-data/wiki (SKILL.md, 14 references, 2 scripts) translated to
  English. Generated document names follow one glossary; validate_kb.py
  still recognises headings of knowledge bases built by the previous
  release, matched by code point so the source stays ASCII.

* fix(skills): prune only files the CLI packaged, let local skills win by name

Review follow-up on #699.

- PACKAGED_SKILL_FILES lists every file a release ever wrote under skills/,
  as the union of `git ls-tree -r <tag> -- skills/` over all 91 tags. The
  prune removes those paths and the directories they leave empty; a file a
  member added is kept, its directory with it, and pull says which and why.
  The stub directory loses its six known references by name instead of
  "everything that is not SKILL.md". Python bytecode of a script we shipped
  counts as ours, so a __pycache__ does not strand the tree.
- locateSkill searches the team repo, then installed agents, then the
  package. A directory a member created under `codebase`, `default`,
  `learning` or `share` is the skill they asked about, and the recall gate
  does not apply to it.
- A guard test fails when a file ships under skills/ without being recorded
  in the manifest, which a later migration would otherwise leave behind.

* fix(skills): close the last recall bypass, uninstall Codex's shared stub

Review follow-up on #699.

- `skill path` takes a name, always. The argument-less form printed the
  `skill-data/` root, and `<root>/share/SKILL.md` is readable from there —
  the content the gate withholds one command over.
- uninstall discovers skills in Codex's shared `.agents/skills` root, where
  resolveSkillDestination puts the stub whenever the skill already lives
  there. Without it, uninstall reported success and left it behind. Codex
  only, as the legacy prune already does.
- core/SKILL.md said team sharing is enabled by default; getRecallSharing
  defaults it to false. It now says recall is off by default and names
  `teamai recall enable`.

* fix(skills): uninstall by the same ownership rule as pull, quote {SKILL_DIR}

Review follow-up on #699.

- uninstall removed a CLI-owned skill directory whole, undoing one command
  over the guarantee pull makes. It now removes the PACKAGED_SKILL_FILES
  paths through the same removeOwnedFiles, keeps a directory holding a file
  the member added, says which one, and tells the confirmation prompt so it
  no longer promises a directory it will keep. A team-repo skill is synced
  whole and still goes whole.
- Served shell commands quote the placeholder: `python3 "{SKILL_DIR}/..."`.
  Unquoted, an install path with a space ("Program Files", "Application
  Support", a Windows path through Bash) splits into two arguments and the
  documented invocation fails. A test fails on an unquoted occurrence after
  any command word, in SKILL.md or any reference.
- wiki/references/overview.md said the methodology, scripts and agent specs
  are deployed into agent directories. They are not: only the stub is, and
  the rest is served from the installed CLI.

* fix(skills): deploy the stub in reporting-only mode, drop the stale list alias

Review follow-up on #699.

- Reporting-only HTTP pull pruned the legacy trees and deployed nothing, so
  a member on an HTTP team came out of the upgrade with no built-in entry
  point at all. The skip predates CLI-served content: it existed because the
  only deployable unit then needed a team repo. The stub does not — its
  workflows are printed by the installed binary, and `skill get wiki` is a
  local knowledge-base generator that never touches a repo. The stub now
  deploys in every mode, and `reportingOnly` goes with the branch it gated:
  nothing else read it.
- `teamai skill list` called itself an alias for `teamai list skills
  --source all`. It has not been one since it started printing the CLI-served
  catalog underneath. Both descriptions, the generated command reference and
  both usage guides now say what it does.

Refs #678

* fix(skills): carry the TGit provider guide into the served setup skill

#724 landed `skills/teamai/references/provider-tgit.md` and repointed
setup-admin.md and join-member.md at it. Rebasing onto that left the new
file in a tree this branch no longer deploys, and the pointers in bare
`provider-tgit.md` form the served skills do not use.

- move it to `skill-data/setup/references/`, beside the two files that
  cite it, so `teamai skill get setup --full` serves it
- rewrite every pointer to it as `{SKILL_DIR}/references/provider-tgit.md`
- list it in the setup skill's reference table
- add `references/provider-tgit.md` to PACKAGED_SKILL_FILES, so the prune
  removes it from members who pulled a release that shipped it

* fix(skills): make the blocked catalog entry unrepresentable, drop unsafe casts

Review findings from the standards axis, plus the doc half of the prune
count.

- `SkillCatalogEntry` allowed `{blockedByRecall: true, path: '/…'}`, an
  invariant `skillCatalog` then upheld by hand. Split it on
  `blockedByRecall`, so the withheld directory is a type error rather than
  a review catch. Both variants keep the `path` key, so the
  `skill list --json` shape is unchanged.
- `command.commands as Command[]` stripped commander's `readonly` in three
  places. `for…of` and `.find` need no cast.
- `docs/designs/skill-serving.md` still said the prune removes six
  `teamai/references/*.md`; provider-tgit.md makes it seven.

* fix(skills): keep publishing a skill reachable when recall is off

Publishing a skill is `teamai push --skill`, which never consulted recall
(`src/push.ts` names it nowhere). On main the flow shipped in the teamai
skill, ungated. Moving `contribute-member.md` under `share` put it behind
the recall gate, so with recall off — a new team's default — the core
routing table sent the agent to `teamai skill get share`, which exits 1
and tells it to enable recall. Wrong advice for a flow recall does not
touch, and no other path to the instructions.

Move the file to `core`, the skill that already owns `push`, and split the
routing row so publishing and session learnings stop sharing one
destination. The gate itself is right and stays: learnings do need recall.

`share/SKILL.md` already called this "a different flow"; now it points at
`teamai skill get core --full` instead of at its own references.

PACKAGED_SKILL_FILES is unchanged: the legacy path a pre-stub release
wrote is still `teamai/references/contribute-member.md`.

* fix(skills): back up what the prune removes, so no edit is a one-way door

Review finding: `removeOwnedFiles` proves ownership by pathname and
deletes without reading the file, so a member's edit goes with it.

For a path the current package still ships that changes nothing: the old
deployment overwrote it with `overwrite: true` on the same three triggers,
so the edit died either way, at the same moment. The case the objection
gets right is a path a retired release shipped and the package no longer
does — the overwrite never reached it, so the edit did survive, and the
prune is the first thing to remove it.

Copy every pruned file to `~/.teamai/removed-skills/<date>/<tool>/<skill>/`
before removing it. Outside every agent directory, so nothing reads it back
as a skill.

Verifying contents against a hash of each released version was the other
way out, and it is worse: anything not byte-identical is then kept, so one
CRLF checkout on Windows — a platform this project supports — leaves the
whole 176 KB in place and reports success. Backing up gives the same
guarantee without betting the migration on byte equality.

Uninstall keeps deleting outright: there the member asked for the files to
go.

* fix(skills): let no backup failure authorise a delete, give each root its own

Two holes in the backup the previous commit added, both reported in review.

The copy's failure was swallowed at debug level and the delete went ahead
regardless, so a full disk or a read-only home turned the migration back
into the data loss the backup exists to prevent — and the log still named
a backup directory that held nothing. A file whose copy fails is now kept,
counted, and named at warn level; `removeOwnedFiles` returns what happened
instead of a bare boolean, and only a run that copied something names the
directory.

The backup path was `<date>/<tool>/<skill>` with `overwrite: true`, so the
second copy of a name silently replaced the first. Codex prunes the same
skill from `.codex/skills` and the shared `.agents/skills`, and two pulls
share a date. The path now carries a per-run id and the skill root, and the
copy refuses to overwrite rather than clobbering a copy it cannot replace.

Tests cover both: a file where the backup tree must start makes every copy
fail, and the two Codex roots land in separate directories. Each fails
against the previous commit.

* fix(skills): stop at a symlinked root, archive only what is retired

Three review findings, all in the prune.

A symlinked skill directory was walked through. `readdir` follows the link,
every path under it matches a packaged name, and the delete lands in
someone else's checkout. Ownership now stops at the link: the root is
lstat'd, a symlink is refused, and link and target are left alone.

The stub directory was pruned against the full historical file list, which
includes the SKILL.md written one line later. Deployment runs on every
session start, unchanged revision included, so that archived an identical
copy per session forever. Only paths this release no longer ships are
archived now.

Backups were written under the tool's base directory, which under project
scope is the repo root, so they landed in the working tree outside the
generated .teamai/.gitignore. They go to the machine's home.

Also: `skill show <packaged>` resolved the team before the package, so it
failed on a machine that never ran `teamai init` for content that needs no
team. Packaged names resolve first and print without the team-dependent
fields.

* fix(skills): stop at the first link above a skill dir, report a half prune

Findings from a self-review run before pushing, plus the two from the last
review round.

The symlink guard was one level too low. It lstat'd the skill directory, so
the common shape — `~/.claude/skills` itself linked at a dotfiles checkout —
walked straight through: every directory under the link is real. The guard
now walks each component below the tool's base directory and stops at the
first link, which covers the prune and the stub write with one check.
Components at or above the base are not checked: a home directory under a
link is ordinary, and refusing there would disable deployment on those
machines.

The symlink branch borrowed the foreign-files message, so a member was told
"delete the rest yourself" about a directory nothing had touched. Following
that destroys what the guard just protected. It has its own sentence now, in
pull and in uninstall.

`remove()` was not fail-closed the way the backup is: a read-only parent
left the tree half-pruned under a debug line, and a `walkFiles` that threw
returned success. Both are recorded in `notRemoved` and reported.

The backup path gained the base directory: `inheritUserScope` deploys the
user base and then the project base in one process, same tool, same root,
same skill name, and `errorOnExist` turned that collision into files the
second pass could neither archive nor prune.

Docs corrected against the code: the archive path, the tag count (98, not
91, and `teamai-wiki` is excluded), the version line, and the size table.

* fix(skills): route the nudge and skill publishing where they land, classify legacy names as ours

The Stop-hook hint said "run /teamai", but bare /teamai prints the menu and
stops, so following the primary suggestion never reached the share workflow.
It now names an invocation the core skill routes to share, with the
`teamai skill get share` fallback kept. The four docs that quote the hint follow.

The setup skill sent "publish one skill" to `teamai skill get share`, which
handles session learnings and is refused when recall is off (the default);
reusable-skill publishing lives in core's contribute-member reference and needs
no recall. The routing row and the two references that repeated it now point
there.

classifySkill checked BUILTIN_SKILL_NAMES alone, so until the first pull pruned
them, team-wiki-codebase and teamai-share-learnings showed as [local-only]. It
now uses isCliOwnedSkillName, the rule push and uninstall already apply.

* fix(skills): pre-push review — gate the nudge on recall, keep bytecode out of the tarball, report a failed uninstall delete

A review of the whole branch against #678, #730 and the design doc, run before
pushing. What it found and what changed:

- The Stop-hook share reminder was gated on the hint switch alone; recall is off
  by default and `teamai skill get share` refuses then, so the reminder pointed
  at a command that said no. It is withheld while recall is off, the same gate
  the workflow has; the served text about when the prompt appears now matches.
- `npm pack` swept `skill-data/wiki/scripts/__pycache__` into the tarball once
  the e2e suite had run the scripts. Excluded in package.json "files", asserted
  absent in the tarball test, and the e2e run sets PYTHONDONTWRITEBYTECODE.
- The `share` description still offered to publish reusable skills, the flow its
  own body sends to `core`; the sentence is gone.
- `skill show <unknown>` before `teamai init` threw the init error as a stack
  trace; it prints the not-found line and exits 1.
- The stub pre-approved every `teamai` command from the always-loaded unit;
  narrowed to `Bash(teamai skill:*)`, which is all it asks for (#678).
- Six routing lines loaded `core --full` to reach one reference; they name the
  file under `$(teamai skill path core)/references/` instead.
- `uninstall` reported a failed delete as "holds files TeamAI did not put there;
  the packaged files were removed", both false and the error unprinted. It names
  the file and the error; a test makes the stub directory read-only.
- The stub directory archived under `<tool>/.claude-skills-teamai/teamai/` while
  the legacy trees used `<tool>/.claude-skills/<skill>/`; one layout now.
- CHANGELOG entry; dead `isRecallEnabled` import; wiki heading still naming
  `team-wiki-codebase`; JSDoc on the wrong declaration; stale byte counts; the
  usage guides gain the recall refusal and the archive location; the design doc
  records the `--json` deviation, the legacy-name classification rule, the
  uninstall symlink scope and the fail-open wording.

* fix(skills): English-only served content, one link guard for every caller, withhold share from read-only sources

The reviewer flagged Chinese in skills/ and skill-data/ a third time. Both
reach the agent as CLI output, so the stub's trigger keywords, the paired
sample invocations and the Chinese name for TGit go; the agent translates for the user. A test
fails on CJK anywhere under either root.

Pre-push review of the whole branch, and what changed:

- uninstall walked through a linked ~/.claude/skills and deleted the
  packaged files inside the member's dotfiles checkout; pull refused the same
  layout. removeOwnedFiles now owns the guard, so pull, deploy and uninstall
  apply one check: the skills root and the skill directory. A linked
  ~/.claude (stow, chezmoi) is no longer refused, since every other resource
  writes through it and refusing left those machines on the pre-stub trees.
- share was served to read-only HTTP teams, where its last step
  (teamai contribute) always fails; reportingOnly used to skip it. The
  serving gate carries a reason (recall | read-only) with its own message,
  and `skill list --json` reports it as `blockedBy`.
- The bytecode rule claimed any file under any __pycache__; it now claims
  only the .pyc of a shipped script.
- recall disable pruned the shared .agents/skills root for an uninstalled
  Codex; it has deployment's install gate now.
- The source-team guard lost the legacy names when BUILTIN_SKILL_NAMES
  narrowed, so a source removal could delete a legacy tree wholesale.
- Routing: the admin wrap-up and the stub still sent "share what I learned"
  to share without saying it needs recall, and the stub filed "share this
  with my team" (the publish-a-skill phrase) under share. recall enable is
  described as the per-machine override it is, next to the team key.
- {SKILL_DIR} definitions now say how a reference file opened on its own
  spells the directory, since serving resolves the definition too.
- skill show: packaged resolve only when init fails, aligned label, a
  served skill is "served by the CLI, not installed".
- Docs: uninstall removes the archive with ~/.teamai; zh said the whole
  directory is kept; the product overview lacked the recall gate; the design
  doc's release, tag and byte figures were stale; CHANGELOG notes the
  language change of generated documents.

* fix(skills): check every path component below the base for a link, in uninstall too

The previous commit narrowed the guard to the skills root and the skill
directory, so a link at ~/.config or ~/.config/opencode was walked through:
the prune could delete, and deploy write, inside a dotfiles checkout. The
full walk from the tool's base directory is back, and removeOwnedFiles now
requires the base, so uninstall applies it too; each skill directory in the
uninstall plan carries the base its skills root hangs off.

A member whose whole ~/.claude is a link keeps the pre-stub trees and gets
the warning naming the path, as before the previous commit. Deleting through
a link is the one thing the prune must never do.

* fix(skills): withhold the share hint on read-only sources, route legacy names through the gate

contributeHintAllowed checked recall only. The dispatcher already drops this
gitOnly handler for HTTP teams, but the gate now says so itself, so the
reminder never points at a `share` that refuses as read-only wherever it runs.

`skill show teamai-share-learnings` searched the agent directories before
the package, so a legacy tree a pull had not pruned yet was shown with its
path while the gate refused `share`. A legacy built-in name now skips the
agent search and goes to the packaged skill and its gate; ordinary names and
aliases such as `share` keep a member's own directory first.

* fix(skills): deploy and prune built-ins where the tool keeps its skills

deployBuiltinSkills joined baseDir with the configured skills path, while
team-skill sync resolves the directory through skillsDirForTool: OpenClaw's
workspace, and HERMES_HOME for Hermes. Those agents got the stub in a
directory they never read and had their legacy trees pruned from the wrong
place. Deploy, the legacy prune, recall disable and uninstall now resolve
the same directory; the link guard starts at the tool's base directory when
the skills directory sits under it, else at that directory's parent.

* fix(skills): check an external skills root for a link, keep config-load logs off stdout, drop inert allowed-tools

- A skills directory outside the tool's base (HERMES_HOME, an OpenClaw
  workspace) had the guard start at the root itself, so a linked root was
  never checked. It starts one level above now, and a linked HERMES_HOME is
  refused like a linked ~/.claude.
- The share gate loads the config, which can migrate it and report that with
  log.info on stdout: an upgrading machine got that line in `skill get`
  output and in `skill list --json`. Config loading reports on stderr for
  that call; setStderrOnly returns the previous mode so it can be restored.
- `allowed-tools` in the served skills was printed as command output and
  never processed as skill metadata, so it granted nothing. Removed, and the
  test now fails if one comes back. Only the stub's line pre-approves.

* fix(skills): walk the link guard from the scope root, so a linked COPILOT_HOME is refused

skillsGuardBase started at the tool's base directory, which for Copilot in
user scope is COPILOT_HOME, so the walk never checked whether COPILOT_HOME
itself was a link, and pull and uninstall wrote and pruned through it. The
guard now starts at the scope root (home, or the project root), where a link
at or above is ordinary, in deploy, the legacy prune and uninstall alike; a
root configured outside it still has the walk start just above that root.

* fix(skills): keep generated documents in Simplified Chinese, fail on a broken config, quote skill paths

- share and wiki had moved generated learnings and knowledge-base documents
  from always Chinese to the session language. Serving the instructions from
  the CLI does not need that, so both say "Simplified Chinese" again, in an
  English instruction; the CHANGELOG entry follows.
- skill show and skill list treated every autoDetectInit failure as "not
  initialized" and pointed at `teamai init`. requireInit now throws a tagged
  NotInitializedError; only that falls back to the packaged catalog, and a
  malformed or unreadable config propagates.
- `$(teamai skill path …)/…` is word-split in a shell command like an
  unquoted {SKILL_DIR}; all ten occurrences are double-quoted and the quoting
  test covers the form.

* fix(config): raise NotInitializedError only when the config file is missing

loadLocalConfig returns null both for a missing file and for one that fails
to parse, validate or migrate (it logs the reason). requireInit turned every
null into NotInitializedError, so skill show and skill list still fell back
to the packaged catalog and a `teamai init` hint on a broken config. Only an
absent file is NotInitializedError now; an existing one that could not be
used is an error naming its path, in requireInit and the user branch of
requireInitForScope. Covered through the real loader and the built binary.

* fix(skills): prove ownership by content, not path alone; retire the second Codex copy

- The legacy prune and uninstall removed any file at a path a release had
  packaged, so a member's edit, a skill of their own under an old name, or a
  root TeamAI never managed (toolPaths or HERMES_HOME moved) lost its files.
  A file is ours now only at a packaged path and with content a release
  shipped there: PACKAGED_SKILL_DIGESTS records the sha256 of every blob over
  all 99 tags through v0.25.0 and main before the stub, 37 versions across 21
  paths. A skill-root SKILL.md is compared by its body, since releases before
  0.17 shipped no frontmatter and the deploy of the day repaired it on disk.
  The current stub is ours by the packaged copy. Anything else stays.
- Codex reads .codex/skills and the shared .agents/skills, and the stub goes
  to the shared one when a copy lives there; the copy an earlier release left
  in the other root kept its old SKILL.md and references. It is retired by
  the same ownership rule, archived first, and named when kept.
- Tests mock the digest table with a stand-in for shipped content, and a test
  keeps the stand-in on the same paths as the real table.

* chore(skills): carry main's skill edits into the served copies after the rebase

#713 and #736 edited skills/teamai/references/*.md, which this branch moved to
skill-data/setup/references/. Two hunks did not follow the move:
- join-member.md: TGIT_TOKEN is REST-API-only and cannot clone (#713).
- setup-admin.md: the /teamai share entry publishes a reusable skill; a
  session's learnings are automatic (#736), in English as the served text is.
#739's partial config mock is restored in skip-uninstalled-tools.test.ts.

* fix(skills): deploy before pruning, block share on an unloadable config, drop hidden commands from the reference

- Legacy trees were pruned before the stub was written, so a refused or
  failed stub (a link, a read-only directory) left the agent with nothing
  to discover. They go only once the stub deployed for that agent.
- The share gate failed open on any config error. Only a machine with no
  config (NotInitializedError) is served; a config that exists but cannot be
  loaded blocks with its own reason, `blockedBy: "config"`.
- The KB template told agents to run `code-to-knowledge --update`, which
  does not exist; it names `teamai codebase --extract … --incremental`.
- The generated command reference listed hidden hook plumbing (`track`,
  `contribute-check`, `todowrite-hint`, …). It renders what `--help` lists.
- removeEmptyDirs swallowed every rmdir error, so a directory that stayed
  could be reported removed. Only "still holds something" is expected; any
  other failure is reported.

* fix(skills): whole-file ownership, stub before its references, no side effects before the link guard

Review of 327f9cd:
- SKILL.md was compared by its body, so a member who changed only its
  frontmatter lost the file. Every release from 0.16.1 (the first whose
  deploy repaired frontmatter) shipped complete frontmatter, so what is on
  disk is what was shipped: digests are whole files now (42 versions over
  100 tags and main). A link is never ours; bytecode is ours only beside a
  script proven ours by content, decided before anything is removed.
- The stub dir's retired references were pruned before SKILL.md was copied;
  a failed copy left the old skill pointing at files that were gone. The
  stub is written first.
- The Codex destination was resolved with the reconciliation that deletes a
  duplicate, before the link guard ran. It is resolved side-effect free; the
  other copy is handled under the guard by retireOtherCodexCopy, whose
  report now names a failed backup or delete as such.
- A broken project config was skipped by detection, so the share gate
  answered with the user config. findUnreadableProjectConfig reports it via
  an optional sink on detection (no caller changes), and the gate blocks.
  The Stop-hook reminder is withheld on an unloadable config too.
- init announced the stub as ready when nothing was deployed; hook-dispatch
  is hidden (hook plumbing), and the reference says it lists public commands;
  the design doc no longer says teamai-workflow/teamai-import are removed.

* fix(config): report a broken higher-priority project config even when a fallback loads

findUnreadableProjectConfig dropped a recorded error whenever detection
went on to find a later candidate: a broken partition config followed by a
valid legacy .teamai/ config returned null, and the share gate answered with
the fallback's team. It now reports the first unreadable file regardless.
An existing config file that is empty or cannot be read is reported to the
sink too, instead of returning without a word.
2026-09-23 16:15:38 +08:00
pablo bc6943ea30 fix(members): read the default-branch roster as an inherited root after the reports switch (#741)
The orphan-branch switch (#489) made members list and projects members read
only the teamai-reports worktree, so a team whose roster still lives on the
default branch saw "No team members registered" right after upgrading (#735).

The default-branch clone now stays a read-only inherited member root, the way
learnings' already is (#485): listing unions both roots (the reports-branch
copy wins when the same file exists on both), nothing is copied or deleted, and
read-only commands still never publish the reports branch. Member registration
merges against the inherited copy too, so a re-init keeps the original
registeredAt/projects and converges the data onto the branch.

Fixes #735
2026-09-23 15:17:44 +08:00
dvd233 48b3dcb953 feat(hooks): add DeepSeek Harness hook bridge (#689)
Fixes #623
2026-09-23 15:02:34 +08:00
Saul MoroandSaul Moro d80d5a8678 fix(push): namespace new rules and agents from --role/--project (#649) (#698)
* fix(push): namespace new rules and agents from --role/--project (#649)

`--role`/`--project` only ever placed new skills, so a rule pushed with
`--project front-app` landed at `rules/<name>.md` and a new agent at
`agents/<name>.yaml` — both of which `pull` ships to every member. The
flag also collapsed into the project's `skills` namespace, which is the
wrong directory for a rule: a rule is namespaced on the `knowledge` axis,
and the manifest allows the two to differ.

Each pushable type now resolves from its own axis (skills → `skills`,
rules → `knowledge`, agents → `agents`), and the destination is printed
rather than chosen silently. Where the named project declares no
namespace for a type being pushed, the command fails and names it
instead of writing to the shared root.

Only new resources already at the shared root are placed; anything the
scanner namespaced keeps its path (#654), and an open PR's recorded
destination still wins so a force-push never moves a resource.

Also resolves a root-level local rule against its namespaced team copy,
so a rule that was placed on an earlier push is not re-pushed to the
shared root once it merges.

* fix(push): record rule placement in state instead of matching by basename

RulesHandler.scanLocalForPush matched a root-level local rule against the
sole active rules/<ns>/<name>.md by basename. A namespaced team rule is
pulled into a namespaced local directory, so another member's unrelated
root rule with the same name would have been read as a modification of the
team rule and overwritten it under --all.

push now records where it placed each root-level rule (state.placedRules,
name -> team path). The scanner redirects a root-level local rule only when
that record exists and its team file is still present; otherwise the rule
is new. The ambiguity warning goes with the basename index.

Review: https://github.com/Tencent/teamai-cli/pull/698#issuecomment-5770251793

* fix(push): stop on unreadable roles manifest, sync placed rules, resolve in dry-run

Three review findings on top of the #649 placement fix.

A roles manifest that exists but cannot answer — unparseable, or missing the
configured role — no longer falls back to an empty namespace list, which sent a
new rule or agent to the shared root and therefore to the whole team. Only an
absent manifest keeps the pre-manifest fallback, so `loadRolesManifest` now
throws a tagged `RolesManifestNotFoundError` to tell the two apart.

`syncTeamUpdatesToLocal` follows the same `placedRules` record the scanner does,
so a root-authored rule placed under `rules/<ns>/` takes part in the three-way
sync. Without it a teammate's newer version was never synced down and the stale
root copy was pushed over it.

`--dry-run` now runs the recorded-destination and placement steps before it
exits, so it reports where every new resource goes and fails on the same
unresolvable project axis the real command refuses.

* test(push): cover #649 placement with the real CLI across agents and providers

Drives the built dist/index.js against real git remotes, a fake `gh` and a fake
GitLab API, and asserts on the branch content that reached the remote.

The four agents × three providers cover the placement itself; the remaining
cases cover what review round 2 raised — the pre-push sync following
placedRules, an unreadable roles manifest stopping the push, and --dry-run
resolving the same destinations. Reverting any of those three fixes turns
exactly its case red and leaves the rest green.

* fix(push): keep a placed resource maintainable and removable by its author

Three review findings on the placement this PR added.

A placement record only ever meant "push put this here", and the two sides that
read one disagreed about how much it was worth. `placedResourcePath` is now the
single resolver: it validates the record (inside the resource root, namespaced,
no traversal, named after the resource) and both the push scanner and the
pre-push sync go through it, so they cannot drift apart again. The record also
takes precedence over a shared-root file that appears later with the same
basename — mapping the author's copy onto somebody else's rule would push their
content over it.

Agents gained the analogue, `placedAgents`. `AgentsHandler.scanLocalForPush`
only accepts a team source whose namespace is ACTIVE here, so an agent
published with --role/--project into a namespace this directory never
activated was skipped as "no active source" on the author's very next edit:
they could create the agent and then never maintain it.

`teamai remove rules <name>` resolves the same record through the new
`publishedNameFor` hook. The author's copy stays at the rules root, so the name
they type is the bare one, and remove answered "not found" about a rule it had
recorded publishing. It now reports which name it resolved to, deletes the
namespaced team file, and takes the author's root copy with it — left behind,
that copy re-publishes the rule on the next push.

* fix(push): narrow what a placement record grants, and when it is written

Four review findings, each about the record rather than the placement.

`remove` consulted it only after a bare-name match failed, but the LOCAL scan
contributes the bare name whenever the author's own copy has edits — so
`remove rules my-rule` deleted that copy, reported success, and left
`rules/<ns>/my-rule.md` published. The record is now resolved first.

A record is written only for a resource push actually placed: `new`, and
namespaced by this run. Recording a `modified` agent meant a namespace that
happened to be active at edit time became standing permission to keep editing
that agent long after the role or project granting it was dropped.

Records are persisted per group, right after that group reaches the remote,
instead of after every group completes. A failing later group returned early
and took the earlier group's mapping with it, so a resource that WAS pushed
came back misclassified once its PR merged.

And the roles manifest is held to the same rule as `--role` and the projects
manifest: a namespace is one path segment. `foo/bar` wrote an agent below the
depth pull looks at, and read back as namespace `foo` for a rule.

* fix(push): let --role/--project decide which team agent a local edit belongs to

`AgentsHandler.scanLocalForPush` picked the team file to edit by activity
alone, and it runs before the destination is resolved. So `agents/other-ns/vr.yaml`
— an agent this directory never activates — made `push --project front-app`
report "no active source" and push nothing, even though the same stem is
allowed to exist in several namespaces and the flag had named a different one.
The scan now takes the requested namespace, through a new optional
`ScanForPushOptions`; with one named, sources in other namespaces are other
agents, and an absent one means this agent is new there. A shared-root copy
still blocks, and now says why: both would be active at once, which is the
collision pull reports.

`RulesHandler.removeItem` swept the bare basename unconditionally, so
`remove rules fe/foo` deleted an unrelated personal .claude/rules/foo.md. The
bare copy is only ours to delete when this machine's placement record says the
two are the same rule.

`teamai push --help` said both flags target skills.

* fix(push): never place a new resource onto one that is already there

Placement rewrote a new root-level resource to the resolved namespace without
looking at what was at that path. An unrelated local `foo.md` — which the
scanner rightly calls new, since no record maps it anywhere — landed on
`rules/<ns>/foo.md` and replaced somebody else's rule, silently, in a run they
never reviewed. Push now stops and names the file. The same guard covers the
`--role`/`--project` skills override, for new skills only: a modified one is
meant to land on its own directory.

`loadRolesManifest` read through `readFileSafe`, which answers null for every
failure, so a manifest that exists but cannot be read arrived looking exactly
like a missing one — and a missing one is the pre-manifest layout, which sends
new rules and agents to the shared root. The two are told apart now.

`RulesHandler.removeItem` tombstoned only the name it was given. Removing
through a placement record means the author's source is named `<name>` while
the published file is `<ns>/<name>`, and the local sweep skips excluded tools,
so a root copy could outlive the removal there and come back on the next push.
Both names are tombstoned when the record vouches for the bare one.

* fix(push): resolve a placed agent on removal, and collide on either extension

`remove` asked every handler for the published name, but only rules answered.
So `teamai remove agents vr` matched the bare stem and deleted every `vr` in
every namespace — other people's agents included — while the namespaced
`placedAgents` record, keyed by a path the removal never named, survived.
`AgentsHandler.publishedNameFor` resolves it now; the existing sweep already
narrows a `<ns>/<stem>` to one file, since the root directory is one of the
directories it probes. The bare stem is tombstoned alongside the published one
and swept from the tool directories, the same way rules are.

The placement collision check tested the proposed path alone. `pull` reads a
legacy `<stem>.md` as the same agent as `<stem>.yaml`, so a new `.md` landing
beside an existing `.yaml` passed the check and left two copies answering to
one name. Agents are now checked under both canonical extensions.

* fix(remove): make the placed-agent resolution actually reach the command

Round 7 added `AgentsHandler.publishedNameFor` but `remove` only used its
answer when `allNames` also carried that spelling — and `scanTeamForPull`
reports an agent by its bare stem, never `<ns>/<stem>`. So the resolution was
inert on the real command path: `teamai remove agents vr` fell back to the bare
stem and deleted every `vr` in every namespace, exactly as before. The cross
check is gone; `publishedNameFor` has already proved the file is in the team
repo, which is stronger evidence than membership in a list the scans spell
differently per type.

The bare-stem tombstone that round went with it. Agents deploy FLATTENED, so
both the push scan and the post-pull cleanup read a bare tombstone globally:
removing `fe/vr` suppressed and deleted `be/vr` the moment that namespace
became active. Only the published name is tombstoned now. The author's own
flattened copy is still swept, but only where this machine's record says the
file just removed is where push put it — without that, the copy on disk may be
another namespace's deployment.

Covered end to end this time: the new case drives `teamai remove agents vr`
through the built CLI, which is the join the round-7 unit tests skipped.

* fix(push): raise a project agents-axis failure the scan would otherwise swallow

`--project <id>` resolved the agents destination before scanning and dropped
the failure on the floor. A project with no agents namespace then looked
identical to a run with no flag at all: the scan skipped the agent as "no
active source", the item never reached placement, and the command exited 0 with
"No new or modified resources" — on a flag it could not honour. The error is
carried forward and raised as soon as the scan contains an agent. It cannot
wait for the selection the way the skills axis does, because the item that
would prove the axis is needed is exactly the one the scan removes.

`placedResourcePath` matched the recorded filename by prefix, so a record
pointing at `rules/<ns>/foo.backup.md` was trusted whenever that file existed,
and scanning, the pre-push sync and removal would all follow it onto somebody
else's file. The filename must now be exactly the resource's own.

* fix(agents): reach the canonical source, and hold the record to what it proves

Four review findings, all on the agent side of placement.

The single-repo canonical source in `.teamai/agents/` is picked up directly,
never reverse-parsed, and that branch ignored the placement record: a root
`vr.yaml` placed at `agents/fe/vr.yaml` read as new on the next push, and the
collision guard then refused the very agent this machine published. Removal
missed the same directory, so the agent republished itself on the next push —
which a bare-stem tombstone cannot prevent without suppressing that stem in
every other namespace, since agents deploy flattened.

The project agents-axis error now counts only agents that actually need a
destination. A modified agent already in a namespace is written in place, so an
empty agents axis is none of its business; blocking it contradicted the rule
that only new shared-root resources are placed.

And the record is no longer taken as licence to overwrite. It admits a namespace
this directory never activates, which also means `pull` never refreshed a copy
and the pre-push sync does not cover agents — so if the canonical file moved on
since the last pull, push now says so and asks for a pull instead of writing a
stale rendering over whoever changed it.

* fix(agents): deliver recorded agents on pull, and let a named destination win

The staleness guard added last round was defeated by the pull it recommended:
`pull` advances lastPullRev without deploying an inactive namespace, so the
next push saw an unchanged canonical and wrote the stale rendering anyway. It
also never fired right after the first PR merged, when the file did not exist
at lastPullRev.

The guard is gone, and the cause with it. `pull` now delivers an agent whose
placement record names it, so the local copy tracks the team file and the
ordinary comparison is valid — the inactive case stops being special instead of
needing its own machinery. A stem an ACTIVE namespace already claims is left
alone, since agents deploy flattened and the active one is what is deployed
here; the scan follows the same order, treating the record as a fallback rather
than an extra candidate.

Pending-PR reuse matched on type and name alone, so an open PR for a different
resource of the same name captured a push that named another namespace and
force-pushed into that review. Neither silent answer is safe, so the flag the
user typed decides, the open PR is left untouched, and the collision is
reported. This supersedes the original #331/#654 rule that a PR's destination
always won; that rule still holds whenever no destination is named.

* fix(pull): stop revoking the agent pull had just delivered

Self-review of the branch, before the next review round.

Round 11 taught delivery about placement records but not revocation, and both
run in the same pull: `filterAgentsByNamespaces` wrote the agent and
`cleanupInactiveNamespaces` deleted it again, byte-equal to the render so the
data-safety gate passed it straight through. The record-based delivery was
inert and the file churned on every pull. Both halves now resolve through one
exported `selectAgentsForDirectory`, so they cannot disagree — the same
treatment `placedResourcePath` already gives the push scanner and the pre-push
sync.

Two smaller ones from the same pass. `--dry-run` grouped against the unfiltered
pending list, so it reported a destination the real push no longer uses, which
breaks the property that a dry run matches the run it describes. And the
partial-selection warning counted entries the run had already declined to
reuse, contradicting the warning given for them; both now share the filtered
list, which is computed once there is actually something to push.

* fix(pull): stop the stale sweep from deleting the author's own placed rule

`pullAllRules` sweeps a local rule whose name is absent from the desired set.
A rule published into a namespace keeps the author's copy at the rules ROOT
under its bare name, while the desired set holds `<ns>/<name>` — or nothing at
all when that namespace is not active here — so the sweep deleted their own
file, local edits included. The placement record marks it as theirs, and only
while the team file it points at still exists.

Pending-PR conflict detection trusted `PendingPushItem.namespace`, but the
agent scan records a namespaced destination without setting that field, so
those entries slipped past the check and a push naming another namespace could
force-push into the PR under review. The namespace is derived from the recorded
path when the field is absent, and the agent scan now sets it too — the field
was the only thing telling `pendingNamespaceFor` where to put the resource.

* fix(push): defer the agents-axis failure to selection, reload projects.yaml after the pull, and stop a named namespace reusing a shared-root PR

A project with no agents namespace failed before the listing whenever any new
agent was present locally, so a rules-only push under `--project` was blocked
on an agent the user was never given the chance to deselect. Only an agent the
scan itself skipped (`needsDestination`) fails early now — that one never
reaches the listing, so deferring its error means never raising it. A new agent
is listed, and step 4 raises the same error if it stays selected.

`manifest/projects.yaml` was read in `push`, before `pushCore` pulled the team
clone, so a project whose namespaces changed on the remote placed this run's
new rules and agents by the previous pull's mapping. It is read inside
`pushCore` now, after the pull, and in self mode from the fresh worktree.

Pending-PR conflict detection treated a recorded path with no namespace as
non-conflicting, so an explicit `--role`/`--project` reused a shared-root PR's
branch and rebuilt it with the namespaced path, moving a review the user did
not name from "everyone" to one namespace. The shared root is a destination
like any other: it conflicts with any namespace the flag names.

`pull` delivered a rule this machine placed at `<tool>/rules/<ns>/<name>`
beside the author's copy at the rules root, so a tool that loads rules
recursively applied the same rule twice, disagreeing as soon as the team file
moved on. The placement record names the root copy as this rule's local file,
so delivery updates it and removes the namespaced duplicate an earlier pull
wrote. A namespace another member placed is untouched.

* fix(push): stop on a stale clone under --project, retire a renamed canonical agent's recorded file, and prune placement records

A failed refresh of the team clone was only warned about, after which
`--project` resolved every destination from the previous pull's
`manifest/projects.yaml`. A namespace the remote had changed sent this run's
new rules and agents to the members of the old one. `--project` stops now, and
so does a new resource that would resolve from `manifest/roles.yaml`; a team
with no roles manifest resolves from nothing that can go stale and keeps its
behaviour. `--role` names the namespace itself and is unaffected.

In self mode the placement record redirected a root canonical agent to the
recorded file, extension included. `pushItem` writes by the source's
extension, so an author who rewrote `vr.md` as `vr.yaml` had the `.yaml`
written and the `.md` staged: the change never reached the branch and the
`.md` stayed. The destination now keeps the record's directory and the
source's extension, `pushItem` deletes the file it retires, `push` stages that
deletion and moves the record to the new path.

Placement records were written when a branch reached the remote and never
removed. Once the PR was closed unmerged, or the file deleted upstream, the
record pointed at nothing — until another member created the same path, at
which point it came true again and their unrelated resource read as this
author's. `push` and `pull` now drop a record whose target is neither on the
default branch nor awaiting review on a branch origin still has, before
anything reads the records. A record is kept when origin cannot be asked.

* fix(push): record a placement only once it has landed, withdraw it when a shared-root file takes the name, and drop every stale record

Placement records were written when the branch reached the remote, so a PR
closed without merging left one behind for as long as its branch stayed —
and no provider here can say whether a PR is open. The record now travels on
the pending PR entry (`PendingPushItem.placed`, with the blob push wrote) and
becomes a `placedRules`/`placedAgents` record only when that blob is in the
default branch's history for the path: the PR merged, however the platform
merged it. A path that merely exists is not enough, since another member may
have created it after the PR was closed. `push`, `pull` and `remove` settle
this before reading the records; the stale sweep spares a root copy whose
placement is still awaiting review.

`localNameFor` redirected a recorded rule onto the bare root path without
asking whether a shared-root rule of the same name was being delivered too,
so both landed on the one file in loop order, and the next push could follow
the record and carry the shared rule over the namespaced one. Delivery keeps
the namespaced path when the shared root holds that name, and the reconcile
pass withdraws the record with a warning: the root copy follows the shared
rule from then on.

Dropping stale records destructured from the ORIGINAL map each iteration, so
a later deletion put back what an earlier one had removed and only the last
stale record went. The kept entries are rebuilt in one pass.

* fix(push): consume a pending placement once it is recorded

Recording a landed placement left its `placed` mark on the pending entry. Had
the team then deleted the file — which drops the record — and another member
recreated the path, the next reconcile recorded it again: the path existed and
the blob push had written was still in the default branch's history, so both
checks passed, and the unrelated replacement read as this author's resource.
The mark and the blob are cleared when the record is written, so a placement
is recorded exactly once.

* fix(remove): keep placement records until the removal lands, and retire flattened copies

`remove` dropped the placement record as soon as its branch was pushed, so a
retry during review resolved `vr` to the bare stem and removed that agent from
every namespace. Records are now left to the reconcile pass, which drops one
once its file is gone from the default branch, or was deleted since the last
check (`placementsCheckedAt`) even if another member has recreated the path.

A namespaced removal tombstones only `<ns>/<name>`, which never matched the
flattened `<agents>/<name>` copy members hold, so that copy survived pull and
the next push republished it. `AgentsHandler.removedStems` reads the tombstone
as the flattened stem while no namespace still has that agent, for both the
pull cleanup and the push scan. Rules no longer write a bare tombstone, which
swept and suppressed other members' unrelated rules of the same name.

Agent and rule push scans skip tools the member excluded: remove leaves those
copies behind by design, so reading them republished the removed resource.

Landing is proven only by history after the full commit the push branch was
built on, and a placement whose path was deleted after it landed is spent
unrecorded. Single-repo pull no longer reconciles against the member's own
checkout; push and remove still do, in a fresh origin/<default> worktree.

* fix(pull): reconcile single-repo records through origin/<default>, and retire flattened copies per directory

Single-repo pull skipped the reconcile pass, so a merged placement stayed
unrecorded until the next push or remove. It now reads the default branch as
the ref origin/<default> (existence via `<ref>:./<path>`, history up to that
ref) instead of the member's own checkout, and changes nothing when the ref
cannot be resolved.

`placementsCheckedAt` survived its last record, and a record made in the same
run was checked against it, so re-placing a resource at a path deleted earlier
dropped the new record at once. The checkpoint is cleared with the last record,
and records made in this run are not held to it.

`removedStems` retired the flattened stem only when no namespace had it at all,
so an fe member kept a removed fe/vr while an unrelated be/vr existed. It now
asks what this directory is meant to hold, through the same selection pull
delivers with.

* fix(remove): stop on a stale clone, and judge PR conflicts by the destination the flag gives

`remove` ignored a failed refresh and reconciled the stale clone as if it were
the default branch. A placement merged since the last pull was then not
recorded, and the bare name fell back to the stem, removing that agent from
every namespace. `remove` now stops with exit 1 and removes nothing.

Under --role/--project, a pending PR counted as conflicting whenever its
recorded namespace differed from the flag's, although only skills and new
shared-root rules and agents are moved by it. A modified rule already in a
namespace kept its path yet went to a second PR on the same file. Only an
item the flag actually moves can conflict with it now.

* fix(push): prefer an agent's delivered source over the flag, baseline new placements, validate the record's namespace

With --role/--project the requested namespace always chose the team file a
local agent was compared with, so an untouched copy delivered from an active
namespace read as an edit of the requested namespace's agent and overwrote
it. Candidates now follow delivery: an active source (the shared root
included), then this machine's record, and only then the requested namespace.

A placement that landed after the last pull had no `lastPullRev` version, so
the pre-push sync skipped it and a teammate's edit before the author's next
pull was pushed over. Rules take the version the file was added with as their
base; a recorded agent, which has no pre-push sync, is held with a pull-first
message when the team file moved past that baseline.

`placedResourcePath` now requires a safe namespace segment: a backslash in it
is a separator on Windows and walked out of the resource root.

* fix(push): close the round-21 findings on placement, removal and agent sources

- A pending namespaced placement whose name a shared-root file now takes is
  left out of the push with a warning, instead of the open PR being rebuilt
  with the author's copy over the shared file.
- `remove` stops when the placement records cannot be reconciled and saved:
  a missing record sends the bare name to the stem, which spans namespaces.
- An agent skipped for want of a --project agents namespace no longer blocks
  the rest of the push; the error stands only when nothing else is left.
- A placement is marked only with a blob that can prove it landed, and one
  without is spent rather than recorded because its path exists.
- The single-repo `.teamai/rules` scan source is not a tool, so an
  `enabledAgents` list no longer hides it.
- A namespaced agent tombstone retires the flattened stem only where that
  agent could have been delivered; reconcile keeps the author's dropped
  record (`retiredPlacedAgents`) so their own copy still counts.
- Two active same-name agents stay ambiguous under a flag, and a flag naming
  a namespace that already holds the agent is a collision, as for rules.
- In single-repo mode a root copy equal to an older version of its placed
  file is held as stale rather than pushed over a teammate's edit.
- The recorded-agent hold runs only for a changed copy and says to set the
  edit aside first; a pending placement is routed to its PR, not skipped;
  a flag that does not move a shared-root edit says so; several candidate
  namespaces without a terminal fail with a --role hint; a placement that
  landed with other content is reported once.

* fix(push): stop on unsaved records and stale placements, name namespaced agents on remove

- `push` stops, pushing nothing, when the reconciled placement records
  cannot be saved: the sync and the scan read them back from disk, and a
  record that could not be withdrawn still redirects the author's copy.
- On a stale clone every unflagged placement stops, not only one resolved
  from an existing roles manifest: the manifest's absence and the skills
  namespaces detected from the tree are clone state too.
- `remove agents <ns>/<name>` names one namespaced agent; a bare name only
  one namespace has resolves to it, and a bare name found in several places
  is refused rather than removed from all of them.
- A record dropped because its file was deleted and recreated is retired
  like one whose file is simply gone, so the author's flattened copy of the
  removed agent is still recognised.

---------

Co-authored-by: Saul Moro <smoro@ai-lab.knowmadmood.com>
2026-09-23 14:58:21 +08:00
Hill PatelandClaude Sonnet 5 94a0d428c1 fix(env): only stick to a candidate the active profile actually reaches (#682) (#715)
* fix(env): only stick to a candidate the active profile actually reaches (review)

02c93fe's resolveActiveShellProfile scanned every SHELL_PROFILE_CANDIDATE_NAMES
entry for a matching block and returned the first hit, in a fixed order
(.zshrc, .bashrc, .bash_profile, .bash_login, .profile). That's broader
than the Git-for-Windows-forwarding case it was written for: a stale
block a pre-#682 install left in .bashrc would outrank a correctly
order-picked .profile that hasn't been written to yet, since .bashrc
sorts earlier in the candidate list — silently reintroducing #682 for
exactly the installs upgrading through this fix, with doctor unable to
catch it because the stale block is well-formed where it sits.

Reworked to start from detectShellProfile's order-based pick (the file
the current environment actually reads) and only diverge from it when
that pick's own content references another candidate by a home-relative
path (~/.bashrc, $HOME/.bashrc) — the shape Git for Windows' generated
forwarding file actually takes. A block sitting in a candidate the pick
never reaches is no longer preferred over the pick, regardless of what
it contains.

Also caught and fixed a case of exactly the failure mode this PR is
about: the first cut of the forwarding check was a bare substring match
on the candidate's filename, and my own test's plain-English comment
("...unrelated to .bashrc") satisfied it. Tightened to require the
home-relative reference form a real sourcing line uses.

Verified both scenarios end-to-end on a real Windows host:
- The exact bot-reported upgrade case (stale .bashrc block, empty
  .profile, no forwarding between them): pull now writes into .profile
  and correctly flags .bashrc as stale; doctor reports delivery healthy.
- The Git-for-Windows forwarding case from the prior round: still
  sticks to .bashrc through the generated .bash_profile, no duplicate,
  no stale-block warning.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(env): match real source commands, resolve reachability transitively (review)

Two P1s from the bot's review of #715:

- resolveActiveShellProfile's reachability check was a bare substring
  search on the active pick's content. A comment mentioning a filename
  (never executed) or a longer file sharing the same prefix
  (~/.bashrc.local) would both satisfy it, letting a stale block win
  the same way #682 did. Replaced with referencesCandidate(): strips
  full-line comments, splits each remaining line into statements on
  &&/||/;, and only counts a statement whose first word is literally
  `.` or `source` and whose second word is an anchored home-relative
  reference to exactly that candidate.

- The check only followed one hop: .bash_profile sourcing .profile
  sourcing .bashrc (the common Debian .profile pattern, sourcing
  .bashrc for interactive shells) would miss a block two hops away and
  inject a duplicate. Reworked into a loop that walks the chain of
  files the pick actually sources, with a visited set for cycle
  protection, stopping at the first one that carries the block.

Also fixed the P2: EnvHandler.detectShellProfile's doc comment still
claimed it "stays on whichever candidate already carries this scope's
block" unconditionally, which stopped being true once reachability was
required.

Verified end-to-end on a real Windows host:
- The new two-hop chain (.bash_profile -> .profile -> .bashrc, block
  in .bashrc): resolves to .bashrc, no duplicate, doctor fully clean.
- Re-ran the Git-for-Windows one-hop scenario and the #682 upgrade
  scenario from the prior round — both still correct, no regression.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(env): search every referenced candidate, respect || conditionality (review)

Two more P1s from the bot's round-10 review of 75f3eac:

- The traversal committed to the first referenced candidate in
  SHELL_PROFILE_CANDIDATE_NAMES's fixed priority order and gave up if
  that branch was a dead end, instead of trying every candidate the
  current file actually references. Git for Windows' own generated
  .bash_profile sources both .bashrc and .profile in one file — if the
  real block sits in .profile but .bashrc (sorting earlier) has none,
  the walk stopped at .bashrc without ever trying .profile. Reworked
  into a breadth-first search over the whole reference graph.

- Splitting statements on `||` treated its right side as unconditionally
  reached, but `||`'s right side only runs if the left side fails,
  which isn't something this code can establish. `source ~/.profile ||
  source ~/.bashrc` would mark .bashrc reachable even when .profile
  succeeds. Statements no longer split on `||`; a `source`/`.` sitting
  only after it is folded into its left side's statement and never
  recognized as its own reference, so it's never preferred over a
  block the left side already reaches. Conservative by construction:
  worst case is falling back to the order-based pick (the pre-#693-fix
  behavior), never a false "reachable".

Verified the exact branching scenario end-to-end on a real Windows
host: .bash_profile with the literal Git-for-Windows-generated content
(sources both .bashrc and .profile), .bashrc empty, real block in
.profile — resolves to .profile, no duplicate, doctor fully clean.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(env): only trust verifiable && and || conditions, ignore if bodies (review)

Two more P1s from the bot's round-11 review of aaa1142, both about
referencesCandidate() trusting shell control flow it can't actually
evaluate:

- Any `&&` was treated as making its right side reachable, without
  checking what the left side's condition even was. A guard like
  `[ "$TERM_PROGRAM" = vscode ] && source ~/.bashrc` would mark
  .bashrc reachable unconditionally, even though it only runs inside
  VS Code. Also flagged: a source sitting inside a multiline `if`
  body looks, line by line, identical to a top-level one.

- Folding `||`'s right side into its left statement (the round-9 fix)
  went too conservative the other way: `source ~/.profile ||
  source ~/.bashrc` DOES guarantee .bashrc runs when ~/.profile
  doesn't exist, and the resolver was never even trying it.

Rather than growing another ad hoc regex tweak, rewrote
referencesCandidate() around what it can actually verify without a
real shell parser:

  - Unconditional: a bare `. REF` / `source REF` — but nothing inside
    an `if` block counts, conditional or not. An `if`'s condition is
    opaque to a line scanner; trusting some conditions and not others
    would just be guessing.
  - Existence-gated `&&`: only the self-referential idiom
    `test -f REF && . REF` / `[ -f REF ] && . REF`, where the tested
    path and the sourced path are the same candidate — the one `&&`
    condition this code can independently verify, by visiting that
    candidate itself later in the search.
  - `||` fallback: the left side always counts (always attempted);
    the right side counts only when the left side's own target file
    does not exist on disk — the one case an `||` fallback is
    actually guaranteed to run.

Anything this can't resolve either way is never trusted: the search
just doesn't queue that candidate, and the caller falls back to the
order-based pick — at worst a harmless duplicate block (the
pre-#693-fix behavior), never a false "reachable" that would
reintroduce #682.

Verified end-to-end on a real Windows host: re-ran the core
Git-for-Windows two-pull scenario from #693 (self-referential &&,
still recognized) with no regression. Added 3 unit tests for the new
boundaries: || recognized when the left target is missing, a
non-existence && condition rejected, and a source nested inside an
if block rejected.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* docs(env): document transitive chaining and the verifiable-reference boundary (review)

Round-11 P2: both docs described only a single directly-referenced
candidate, but the resolver has followed transitive chains since
75f3eac and now only trusts specific verifiable && / || forms (60a2da0).
Describes the Debian .profile -> .bashrc two-hop case alongside the
Git-for-Windows one, and names the three reference shapes recognized
(bare source, self-referential existence-gated &&, existence-checked
|| fallback) and that if-bodies are never trusted.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(env): validate reference quoting, credit &&'s left side, generalize block-skip (review)

Round 12 found three more real gaps in referencesCandidate(), plus one
I agree isn't worth chasing further (see PR reply):

- The quote check accepted `source "~/.bashrc"` and `source
  '$HOME/.bashrc'` as valid references, but a shell never tilde-expands
  inside any quotes and never variable-expands inside single quotes —
  both source a literal, near-certainly nonexistent path. Tightened to
  the three forms that actually expand: bare `~/name`, and `$HOME/name`
  either bare or double-quoted.

- `&&`'s left side is always attempted, the same as `||`'s — `source
  ~/.bashrc && echo ready` does reach .bashrc regardless of the
  trailing command, but the old "whole statement must be exactly `.
  REF`" check missed it. The leftmost command before the first `&&` (or
  no `&&` at all) is now checked the same way `||`'s left side already
  was.

- Only `if`/`fi` was tracked, so a source inside an uncalled function,
  a non-selected `case` arm, or a loop body — none of them any more
  guaranteed to run than an `if` body — was wrongly treated as
  top-level. Generalized the "don't trust it" depth counter to cover
  for/while/until, case/esac, and function/brace groups too, sharing
  one counter since we only need to know whether we're inside *any* of
  them, not which one.

Declined to extend if-body trust to cover the standard nested Debian
`.profile` template (`if [ -n "$BASH_VERSION" ]; then if [ -f
"$HOME/.bashrc" ]; then . "$HOME/.bashrc"; fi; fi`) — doing so would
mean trusting the outer `$BASH_VERSION` check, which is exactly the
class of unverifiable shell condition this design has refused since
round 11. Fixed the docs instead: they previously (incorrectly)
claimed this exact template was recognized; now they say plainly that
nested conditionals of any kind fall back to the order-based pick.

Verified end-to-end on a real Windows host: re-ran the Git-for-Windows
two-pull scenario unaffected. Added 6 unit tests for the new
boundaries (invalid vs. valid quoting, &&'s left side, function/case/
loop bodies). 41/41 in shell-profile.test.ts.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(env): handle comments, line continuations, heredocs, and chained && in profile scanning (review)

Round 13 review found five genuine structural gaps in referencesCandidate,
all fixed by moving open/close-block detection to per-statement (post
`;`-split) instead of per-line, and adding a logicalLines() preprocessing
pass:

- Backslash-continued lines were scanned independently, losing the
  conditional context of the line they continue (`cond && \` followed by
  `source X` on the next line looked unconditional).
- A one-line `if ...; then ...; fi` only incremented depth (matched via
  the whole-line "opens" check) and never saw its own `fi` close it,
  permanently disabling recognition of every later unconditional source
  in the file. Two-line function definitions (`fn()` then `{` on its own
  line) double-incremented for the same reason.
- The existence-gated `&&` guard was fully anchored, so a guarded source
  followed by further `&&`-chained commands (`[ -f X ] && . X && export Y`)
  didn't match even though the guard still holds.
- Comment stripping only skipped whole-comment lines; a comment following
  a semicolon on the same line was still split into a "real" statement.
- Heredoc bodies were scanned as literal executable lines.

Declined the sixth (recognizing the Debian/Ubuntu nested
`if [ -n "$BASH_VERSION" ]; then if [ -f ... ]; then . ...; fi; fi`
template) for the same reason given in review round 12: the outer
condition is unverifiable without a real shell, and this resolver's
explicit, repeatedly-restated design boundary is to never trust an
unverifiable condition — falling back to the order-based pick (a
harmless duplicate block) is the intended safe behavior there, not a bug.

Verified with 6 new unit tests (47/47 passing) plus a standalone real-fs
script driving the actual resolveActiveShellProfile against a scratch
HOME for all seven round-13 scenarios (all pass). Full suite unchanged
at the pre-existing 30-failed-file/66-failed-test Windows-host baseline.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(env): quote-aware statement splitting, subshells, dead code after return/exit, N-way || (review)

Round 14 review found six more genuine gaps in referencesCandidate, all
fixed:

- The `;`/`&&`/`||` splits were plain `String.split`, so a separator
  character inside a quoted argument (e.g. `printf '%s' 'x; source
  ~/.bashrc; y'`) was treated as a real statement boundary, inventing an
  executed source out of string data. Added splitTopLevel(), a small
  quote-aware splitter (tracks single/double-quote spans, skips
  separators inside them) used everywhere a naive split was previously
  used.
- `(...)` subshells weren't tracked as an unverified-block construct —
  a source inside one always runs, but its exports never reach the
  caller, so it must not count as reaching a candidate any more than an
  `if` body does. Added to opensUnverifiedBlock/closesUnverifiedBlock
  alongside the existing if/for/while/until/case/function handling.
- An unconditional, top-level `return`/`exit` ends the file's control
  flow right there; anything textually after it was still being scanned
  as if reachable. Added a `halted` flag set on a bare return/exit
  statement, gating everything after it for the rest of the scan.
- `sourceOf` required the source's argument to be the entire statement,
  so `. "$HOME/.bashrc" 2>/dev/null` and `source ~/.bashrc extra_arg`
  (both valid, both really sourcing the target) went unrecognized.
  Relaxed to capture just the first argument and allow anything after
  it.
- The `||` fallback only handled exactly two operands — a three-way
  chain like `source ~/.profile || source ~/.bash_login || source
  ~/.bashrc` wasn't recognized at all, not even the always-attempted
  left side. Generalized to N operands: each one counts only when every
  operand before it is a recognized source whose target is verifiably
  missing from disk.
- Multiple heredocs opened by one command (`cat <<A <<B`) only tracked
  one terminator, so the second heredoc's body was scanned as real
  statements once the first terminator was seen. heredocEnd is now a
  queue of terminators consumed in order.

Declined the seventh finding again (the Debian/Ubuntu nested `if
[ -n "$BASH_VERSION" ]` template) for the same reason given in rounds 12
and 13: the outer condition is unverifiable without a real shell, and
this resolver's explicit design boundary is to never trust one — the
order-based-pick fallback (a harmless duplicate block) is the intended
safe outcome there, not a bug.

Verified with 8 new unit tests (55/55 passing) plus a standalone real-fs
script driving the actual built resolveActiveShellProfile for all nine
round-14 scenarios (all pass, including confirming the Debian pushback
case is unchanged). Full suite unchanged at the pre-existing
30-failed-file/66-failed-test Windows-host baseline.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* refactor(env): replace the growing ad-hoc shell scanner with a narrow, closed recognizer (review)

Round 15 review found nine more genuine parsing bugs, most of them direct
consequences of the general-purpose statement/operand machinery added in
rounds 13-14 (quote/escape-aware `;`/`&&`/`||` splitting, N-way `||`
chains, trailing-argument tolerance on `source`). It also included a
meta-finding, correctly: this had grown into a large, incomplete ad-hoc
shell parser for what should be a narrow forwarding-detection case, and
each round's fix was mostly patching bugs the previous round's own
machinery introduced. Full shell parsing is undecidable without a real
shell; chasing it one adversarial regex at a time was never going to
finish, and it was already producing real regressions (the round-14
`sourceOf` relaxation meant to recognize valid trailing arguments also
started recognizing `source ~/.bashrc | cat` and `source ~/.bashrc &`,
both of which run in a subshell and never actually reach the caller).

Replaced `referencesCandidate`'s open-ended grammar with a closed
recognizer of exactly two forms, each matched as a complete logical line:

- bare unconditional `. REF` / `source REF`
- the self-referential existence guard `test -f REF && . REF` /
  `[ -f REF ] && . REF` — the literal line Git for Windows itself
  generates

Deleted entirely: quote/escape-aware statement splitting (no longer
needed — nothing is split into statements anymore), `||` fallback
handling (both the original two-operand and round 14's N-way
generalization), trailing-argument/redirection tolerance on `source`
(the source of the pipe/background regression above), and
comment-stripping (unnecessary now — a line with anything extra on it
simply fails the exact-match check, which is a large part of why the
statement machinery could be deleted rather than just patched again).

Kept, since dropping them would reopen a real false-positive risk rather
than just narrow scope: block-depth tracking for
`if`/`for`/`while`/`until`/`case`/`select`/function/subshell/brace-group
(content inside is either conditional or non-propagating, generalized
this round with `select` and a fixed one-liner if/for/while/until/case
collapse so a self-contained one-liner doesn't corrupt depth tracking for
the rest of the file), heredoc body skipping (fixed three real bugs in
it: a `<<<` here-string was mistaken for a `<<` heredoc and swallowed the
rest of the file; a non-`-` heredoc's terminator was compared with
`.trim()`, letting an indented look-alike end it early; the delimiter
charset was `\w` only, missing real delimiters like `END-CONFIG`), a
`return`/`exit` halt flag (cheap, and the alternative — textually dead
code after an unconditional exit still being scanned — is a genuine
false positive, however unlikely the pattern), and joining a line ending
in `\`, `&&`, or `||` onto the next (real, unremarkable shell
continuation with no backslash required for the latter two — the risk
this closes isn't hypothetical: an unrelated trailing `&&` followed by an
unconditional-looking `source` on the next line is exactly the shape
that would have produced a false "reachable").

Declined the Debian/Ubuntu nested-`if` finding a fourth time, unchanged
from rounds 12-14: the outer `$BASH_VERSION` check is unverifiable
without a real shell, and this resolver's explicit boundary is that an
unverifiable condition is never trusted. The `||`-existence-only pushback
from round 14 is now moot — `||` isn't recognized in any form.

Net change to shell-profile.ts is negative (-244/+something smaller)
despite fixing more bugs than it added, confirming this is a real
simplification rather than another round of patches. Verified with an
updated unit test suite (61/61 passing — six tests for now-out-of-scope
behavior replaced with tests confirming the safe fallback, new tests
added for every round-15 fix that was kept) and a standalone real-fs
script against the actual built resolver covering all twelve round-15
scenarios (all pass, including the real motivating Git-for-Windows case
and the still-declined Debian template). Full suite unchanged at the
pre-existing 30-failed-file/66-failed-test Windows-host baseline.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-23 14:49:23 +08:00
Saul Moro 94eb1484bc fix(init): refuse provider logins without a terminal instead of hanging (#711) (#713)
* fix(init): refuse provider logins without a terminal instead of hanging (#711)

`teamai init` with no session spawned `gh auth login --web` (or `gf auth
login`, `cnb login`) with inherited stdio and waited for a browser device
flow nobody could complete, about five minutes for GitHub, then exited
with the provider's error and no hint of the missing credential.

Cause: the non-TTY guard lived only in utils/prompt.ts. A login is a child
process that owns the terminal, so it never went through that guard.

- `isInteractive()` in utils/prompt.ts: stdin is a TTY and neither `CI`
  nor `TEAMAI_NONINTERACTIVE` is set. Every prompt and the four
  prompt-semantics `isTTY` checks use it; the six hook-payload checks are
  untouched.
- github, tgit and cnb logins throw before spawning when not interactive,
  naming the token variable, the way gitcode already did.
- index.ts exports GIT_TERMINAL_PROMPT=0 when not interactive, so a
  missing clone credential fails at once instead of prompting or opening
  a credential helper dialog. An explicit caller value wins.
- e2e test with a fake `gh` whose `auth login` sleeps: exit 1 in under a
  second naming GITHUB_TOKEN, also under CI=true.

Closes #711

* fix(init): close every git prompt and point TGit at the credential that works

Review follow-up on #713.

- utils/git-env.ts: GIT_TERMINAL_PROMPT=0 only closed git's own terminal
  question. The askpass chain (GUI dialog), ssh's passphrase / unknown-host
  question through /dev/tty, and Git Credential Manager's window each still
  parked an unattended clone until the 180s timeout. All four are now closed
  together (GIT_ASKPASS=echo, GIT_SSH_COMMAND='ssh -o BatchMode=yes',
  GCM_INTERACTIVE=never), each only where the caller set nothing.
- tgit: the guard suggested exporting TGIT_TOKEN, which cannot make an
  unattended run succeed — the PAT is REST-API-only and git.woa.com's git
  endpoint rejects it, so `gf auth whoami` still fails and the clone still has
  no credential. The message now names `gf auth login` (whose stored credential
  is the one that works) and says why the token is not it. Docs follow.
- local-agent: keep askViaTty's non-interactive decline synchronous. Awaiting
  the prompt module's import before declining shifted hook-path timing enough
  to break the once-per-session binding hint (local-agent.test.ts).

* fix(git-env): append batch mode to core.sshCommand instead of replacing it

Review follow-up on #713.

GIT_SSH_COMMAND overrides core.sshCommand rather than extending it, so setting
it blindly dropped a configured custom key, ssh binary or wrapper and left the
run unable to authenticate at all. The value is now composed: read
core.sshCommand and append `-o BatchMode=yes`, or use plain `ssh` when nothing
is configured. A command that already decides BatchMode is left alone, and the
config read is skipped entirely when the caller set GIT_SSH_COMMAND.

Test isolation, so the suite's own result can be trusted:

- shell-profile.test.ts: the three Windows cases never stubbed SHELL, and
  detectShellProfile reads it before the platform branch — a suite run from a
  zsh login shell resolved .zshrc and failed them without ever reaching the
  Windows branch. CI runners use bash, which is why only local runs saw it.
- local-agent.test.ts: the once-per-session binding-hint markers live in
  os.tmpdir() under one shared key, so a leftover marker decided whether the
  next test emitted a hint, and concurrent runs competed for the same paths.
  Each test now gets its own temp directory, which makes the markers per-test
  by construction.

Full suite: 3788 pass, 0 failures, five consecutive runs.

* fix(git-env): leave ssh to each repository instead of a process-wide override

Review follow-up on #713.

GIT_SSH_COMMAND is the only way to reach ssh's batch flag, and it overrides
`core.sshCommand` for *every* later git operation, not just the one the value
was derived from. Reading the launch directory's config and exporting it
process-wide therefore pushed that repo's key or wrapper onto the managed team
repo, and the plain default suppressed a `core.sshCommand` the managed repo had
configured for itself. Prompt suppression must not reach a repository's
transport, so the variable and the `git config` read are gone.

What remains is the three variables that name a prompt and nothing else, so one
value is right for every repository a run touches: GIT_TERMINAL_PROMPT=0,
GIT_ASKPASS=echo and GCM_INTERACTIVE=never.

An ssh remote that would still ask is now documented as the caller's to close,
per repository (`git config core.sshCommand 'ssh -o BatchMode=yes'`) or per run
(`GIT_SSH_COMMAND`). Measured first: with stdin closed, ssh's own tty read hits
EOF and fails in about a second, so the unattended paths this PR is about do
not depend on the flag.

Also reverts the shell-profile.test.ts and local-agent.test.ts isolation edits
from the previous round: neither traces to the unattended-login fix, so they
belong in their own PR.

* docs(providers): mark the provider logins interactive-only (#711)

docs/providers.md still described `teamai init` as running `gh auth login`,
`gf auth login` and `cnb login` unconditionally. Each now happens only in an
interactive terminal; an unattended run fails at once naming the credential to
prepare (a token for GitHub and CNB, a prior `gf auth login` for TGit, since a
TGIT_TOKEN PAT is REST-API-only and cannot clone).
2026-09-23 10:41:13 +08:00
Ben YounesandClaude Opus 5 b91b6dfcae fix(hooks): list each tool's own built-in hook set (#718)
* fix(hooks): list the built-in hooks each tool really receives

`hooks list` rendered builtinHookDefs('claude') for every tool, so the built-in
block described Claude's hook set no matter which tool the row was for:
Copilot's SessionEnd hook never appeared, while tools that receive no hooks at
all were credited with six.

The displayed set is now derived from what each tool actually receives through
reconciliation, and a tool with no hook surface is omitted rather than shown an
invented list.

Fixes #717

* fix(hooks): report adapter-driven tools by their generated artifact

`hooks list` probed a settings file per tool, so Hermes, OpenCode and
OpenClaw — which reconciliation installs as one generated script/plugin/
handler each — fell through to the generic branch and were reported as
"not configured" even right after `hooks inject` wrote their hook. OMP
already had a bespoke branch for this.

Resolve that artifact per adapter and use its presence as the status, the
same rule OMP used, so the status column matches the built-in block.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(hooks): status against the effective built-in set and the user plugin

Two status-column defects the per-tool listing exposed:

- `getHookStatus` checked the unmodified `builtinHookDefs(tool)`, so a
  built-in the team disabled through hooks.yaml was still expected on disk
  and every tool read `missing` right after a correct reconciliation. It
  now takes the same §4.8 override reconciliation applies.
- The OpenCode artifact was probed under the config scope's base dir, but
  `reconcileOpencodePlugin` always installs the single plugin under the
  user path, so a project-scope config reported `missing` after a
  successful injection.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(hooks): require every generated file before reporting installed

The adapter status probe accepted a single file, so an OpenClaw
installation missing its handler.ts — the file HOOK.md points at, without
which no hook runs — still read as `installed`. Check every generated file
the adapter writes and report `installed` only when all are present.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-23 10:37:28 +08:00
Saul Moro cd3e0e6ef5 fix(hooks): stop the Stop hook nudge reaching the user twice (#720) 2026-09-22 22:47:35 +08:00
Saul Moro 2ed17e4fb2 feat: scope hooks, MCP servers and env variables by logical project (#700) 2026-09-22 22:44:56 +08:00