@team-ai/teamai-cli 0.40.8 → 0.40.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/dist/cli.js +254 -64
  3. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -21,6 +21,8 @@ All notable changes to this project will be documented in this file. See [standa
21
21
 
22
22
  ### Changed
23
23
 
24
+ - `teamai import --dir`, `--from-repo`, `--from-repo-list` and `--from-org` exit 1 when a codebase's deep enrich leaves component or architecture docs missing or fails, and print the command that resumes it: in a team repo the same import without `--incremental`, keeping `--max-files`, `--domain` and `--ssh` (`--from-repo <url>` for each unfinished repo of a batch), with `--output` `teamai codebase --deep-enrich --output <dir>`. The extracted evidence is still published, and a deep enrich error is now a warning instead of a debug line. A deep enrich refused at a symbolic link says to replace it before retrying. The teamwiki update of `import --from-mr` and `teamai ci extract-mr`, and `codebase --upgrade-wiki`, still exit 0 (for [#1500](https://github.com/Tencent/teamai-cli/issues/1500)).
25
+ - `teamai init --http` exits 1, before it writes anything, when the HTTP local agent already uses another endpoint or token; `--force` replaces it as before. Running it again with the same endpoint and token succeeds, and a first `init --http --scope user` now sets up the local agent and its token file, which it used to skip without saying so. An endpoint in `TEAMAI_HTTP_ENDPOINT` does not count as an existing local agent. `teamai source add-http` on the endpoint already set up, without `--token`, keeps the stored token instead of clearing it (for [#1500](https://github.com/Tencent/teamai-cli/issues/1500)).
24
26
  - `teamai pull` exits 1 when the team repo cannot be fetched, as it already did for a pinned ref. A pull a session hook or git hook runs (`--silent`) still exits 0 and records the failure as before (for [#1500](https://github.com/Tencent/teamai-cli/issues/1500)).
25
27
  - The friction reminder offers the `session-close` workflow, which teams can override with `workflows/session-close.yaml`. It fires on the same Stops as before, at most once per session, and keeps its old text, naming `teamai skill get share`, in a session teamai launched, in a workflow worktree, in an unattended session, while the session drives a workflow run that is not done, and when the team's `session-close` sets `invoke: deny`. A session resumed more than a day after its reminder is no longer reminded again. In the dashboard, attended `ask` now reads "proposed when the friction reminder offers session-close" (for [#1388](https://github.com/Tencent/teamai-cli/issues/1388)).
26
28
  - Member settings in `~/.teamai/config.yaml` now apply in every workspace and self scope whose own config does not set them, also in workspaces of other teams, and that file needs no `repo` or `username`. A member with a user install who set one there for user scope only, such as `recallEnabled`, `coAuthorEnabled`, `usageReportEnabled` or `workflows.*`, sees it apply in their workspaces too. `teamai doctor` lists each member setting with the level that set it. An AI call fails when the workspace config where it runs cannot be read, a bad `workflows.allow` in `~/.teamai/config.yaml` stops workflow commands, the HTTP local agent reads `codexTrustEnabled` from that file, and a stop hook prices with its scope's `modelAliases` (for [#1459](https://github.com/Tencent/teamai-cli/issues/1459)).
package/dist/cli.js CHANGED
@@ -55760,24 +55760,40 @@ function processStarts() {
55760
55760
  function recordGroup(child, dir) {
55761
55761
  const start3 = child.pid === void 0 ? void 0 : processStarts()?.get(child.pid);
55762
55762
  if (child.pid === void 0 || start3 === void 0) return;
55763
- const file = path49.join(dir, GROUP_FILE);
55763
+ const body = JSON.stringify({ pid: child.pid, start: start3 });
55764
+ writeGroup(path49.join(dir, `${GROUP_PREFIX}${child.pid}.json`), body);
55765
+ writeGroup(path49.join(dir, LEGACY_GROUP_FILE), body);
55766
+ }
55767
+ function writeGroup(file, body) {
55764
55768
  const temporary = `${file}.${process.pid}.tmp`;
55765
55769
  try {
55766
- fs30.writeFileSync(temporary, JSON.stringify({ pid: child.pid, start: start3 }));
55770
+ fs30.writeFileSync(temporary, body);
55767
55771
  fs30.renameSync(temporary, file);
55768
55772
  } catch {
55769
55773
  }
55770
55774
  }
55771
55775
  async function stopRecordedGroup(dir) {
55772
- const file = path49.join(dir, GROUP_FILE);
55773
- let recorded;
55776
+ for (const file of await recordedGroups(dir)) {
55777
+ const recorded = await readGroup(file);
55778
+ if (recorded !== void 0) await stopGroup(recorded);
55779
+ await fs30.promises.rm(file, { force: true });
55780
+ }
55781
+ }
55782
+ async function recordedGroups(dir) {
55783
+ let names2;
55774
55784
  try {
55775
- recorded = ProcessGroupSchema.parse(JSON.parse(await fs30.promises.readFile(file, "utf8")));
55785
+ names2 = await fs30.promises.readdir(dir);
55776
55786
  } catch {
55777
- return;
55787
+ return [];
55788
+ }
55789
+ return names2.filter((name) => GROUP_FILE.test(name) || name === LEGACY_GROUP_FILE).map((name) => path49.join(dir, name));
55790
+ }
55791
+ async function readGroup(file) {
55792
+ try {
55793
+ return ProcessGroupSchema.parse(JSON.parse(await fs30.promises.readFile(file, "utf8")));
55794
+ } catch {
55795
+ return void 0;
55778
55796
  }
55779
- await stopGroup(recorded);
55780
- await fs30.promises.rm(file, { force: true });
55781
55797
  }
55782
55798
  function signalGroup(pid, name) {
55783
55799
  try {
@@ -55892,13 +55908,15 @@ function stopProcess(child, exit, detached) {
55892
55908
  };
55893
55909
  return (initial = "SIGTERM") => stopping ??= stop(initial);
55894
55910
  }
55895
- var ProcessGroupSchema, GROUP_FILE;
55911
+ var ProcessGroupSchema, LEGACY_GROUP_FILE, GROUP_PREFIX, GROUP_FILE;
55896
55912
  var init_process_stop = __esm({
55897
55913
  "src/tool-launch/process-stop.ts"() {
55898
55914
  "use strict";
55899
55915
  init_zod();
55900
55916
  ProcessGroupSchema = external_exports.object({ pid: external_exports.number().int().positive(), start: external_exports.string().min(1) });
55901
- GROUP_FILE = "group.json";
55917
+ LEGACY_GROUP_FILE = "group.json";
55918
+ GROUP_PREFIX = "group-";
55919
+ GROUP_FILE = /^group-\d+\.json$/;
55902
55920
  }
55903
55921
  });
55904
55922
 
@@ -81541,13 +81559,13 @@ function run(file, args, env3, cwd, reachesCommand) {
81541
81559
  child.on("exit", (code, signal) => settle2(signal ? { kind: "signaled", signal } : { kind: "exited", code: code ?? 1 }));
81542
81560
  });
81543
81561
  }
81544
- async function stepEnvironment(values, scope) {
81562
+ async function stepEnvironment({ values, facts }, scope) {
81545
81563
  const env3 = inheritedEnvironment();
81546
81564
  for (const key of scope.withhold) removeKey(env3, key);
81547
81565
  for (const key of scope.provide) {
81548
81566
  const value = values.get(sameEnvName(values.keys(), key) ?? key);
81549
81567
  if (value === void 0) {
81550
- return { ok: false, failure: { code: "missing_env", message: `Env ${key} has no value on this machine any more. Run teamai env set ${key}, or set it in the environment, then retry the step.` } };
81568
+ return { ok: false, failure: { code: "missing_env", message: `Env ${key} has no value on this machine any more: ${envAdvice([key], facts.declared)}. Then retry the step.` } };
81551
81569
  }
81552
81570
  setKey(env3, key, value);
81553
81571
  }
@@ -81570,6 +81588,7 @@ var init_env_exec = __esm({
81570
81588
  init_logger();
81571
81589
  init_env_reserved();
81572
81590
  init_workspace_children();
81591
+ init_requirements();
81573
81592
  FORWARDED_SIGNALS = ["SIGTERM", "SIGHUP"];
81574
81593
  TERMINAL_SIGNALS = ["SIGINT", "SIGQUIT"];
81575
81594
  SURVIVED_SIGNALS = /* @__PURE__ */ new Set(["SIGPIPE", "SIGUSR1"]);
@@ -82501,13 +82520,13 @@ async function settle(config, record3) {
82501
82520
  return ready;
82502
82521
  }
82503
82522
  async function runPlaceSetup(input) {
82504
- const { config, run: run3, attempt, mode, values, signal } = input;
82523
+ const { config, run: run3, attempt, mode, env: env3, signal } = input;
82505
82524
  const read4 = await readPlaceRecord(config, run3, attempt);
82506
82525
  const recorded = read4.kind === "found" ? read4.record : void 0;
82507
82526
  if (recorded?.phase !== "staged") return void 0;
82508
82527
  const { setup, expiresAt } = recorded;
82509
82528
  const scope = setup.envScope ?? { provide: [], withhold: [] };
82510
- const scoped = await stepEnvironment(values, scope);
82529
+ const scoped = await stepEnvironment(env3, scope);
82511
82530
  if (!scoped.ok) return setupFailed(config, recorded, scoped.failure);
82512
82531
  await markSetup(recorded.dir, "unfinished");
82513
82532
  const settingUp = { ...baseOf(recorded), phase: "setting-up" };
@@ -84398,7 +84417,7 @@ function inProcessClient({ config, env: env3 }) {
84398
84417
  if (placed.kind !== "refused") return placed;
84399
84418
  return request.kind === "adopt" ? { ...ask2, refused: placed.failure.message } : ask2;
84400
84419
  },
84401
- setup: (run3, attempt, mode, signal) => runPlaceSetup({ config, run: run3, attempt, mode, values: env3.values, ...signal ? { signal } : {} }),
84420
+ setup: (run3, attempt, mode, signal) => runPlaceSetup({ config, run: run3, attempt, mode, env: env3, ...signal ? { signal } : {} }),
84402
84421
  start: async (name, { inputs, checkout, caller }) => {
84403
84422
  const cached = await loadCachedWorkflow(config, name);
84404
84423
  const refused2 = invokeRefusal(cached?.definition, caller, { kind: "start" });
@@ -84526,7 +84545,7 @@ async function prepareLeased(input) {
84526
84545
  }
84527
84546
  if (placed.kind === "failed") return failed4(placed.failure);
84528
84547
  const mode = (leased.kind === "leased" ? leased.mode : void 0) ?? resolveRunMode(process.env);
84529
- const failure3 = await runPlaceSetup({ config, run: lock.run, attempt, mode, values: env3.values });
84548
+ const failure3 = await runPlaceSetup({ config, run: lock.run, attempt, mode, env: env3 });
84530
84549
  if (failure3) return failed4(failure3);
84531
84550
  return { data: { ...answer.data, lease: { ...named2.data, cwd: placed.dir, ...placed.prompt !== void 0 ? { prompt: placed.prompt } : {} } } };
84532
84551
  }
@@ -87032,7 +87051,7 @@ async function begin(context, lock, attempt, prepared) {
87032
87051
  const { dir, job: { lease: lease2 } } = prepared;
87033
87052
  const failed4 = (failure3, cause) => fail2(context, lock, { state, attempt, revision: open.revision, failure: failure3, cause });
87034
87053
  if (lease2.executor === "command") {
87035
- const scoped = lease2.envScope ? await stepEnvironment(context.env.values, lease2.envScope) : { ok: true, env: process.env };
87054
+ const scoped = lease2.envScope ? await stepEnvironment(context.env, lease2.envScope) : { ok: true, env: process.env };
87036
87055
  if (!scoped.ok) return failed4(scoped.failure, "place");
87037
87056
  const running = open.phase === "preparing" ? traced(context, preparedRow(state, attempt))?.state ?? state : state;
87038
87057
  await writeSkillState(context.config, lock, running, context.env.secrets);
@@ -93000,6 +93019,7 @@ var init_api_key = __esm({
93000
93019
  var local_agent_exports = {};
93001
93020
  __export(local_agent_exports, {
93002
93021
  DEFAULT_ROUTES: () => DEFAULT_ROUTES,
93022
+ assertNoLocalAgentReplacement: () => assertNoLocalAgentReplacement,
93003
93023
  bindCurrentProject: () => bindCurrentProject,
93004
93024
  bindWorkspaceToProject: () => bindWorkspaceToProject,
93005
93025
  buildAgentIdentityPayload: () => buildAgentIdentityPayload,
@@ -93349,6 +93369,7 @@ async function loadLocalAgentConfig(options2 = {}) {
93349
93369
  }
93350
93370
  return backfilled;
93351
93371
  }
93372
+ if (options2.envFallback === false) return null;
93352
93373
  const envEndpoint = process.env.TEAMAI_HTTP_ENDPOINT ?? process.env.TEAMAI_ENDPOINT ?? process.env.TEAMAI_API_BASE_URL;
93353
93374
  if (!envEndpoint) return null;
93354
93375
  return {
@@ -96084,6 +96105,34 @@ async function tokenStillWorks(config, token) {
96084
96105
  return void 0;
96085
96106
  }
96086
96107
  }
96108
+ function isAgentToken(token) {
96109
+ return token?.trim().startsWith("sk-") === true;
96110
+ }
96111
+ function incomingTokenOwner(existing2, endpoint, token, filterAgents2) {
96112
+ if (!isAgentToken(token)) return void 0;
96113
+ const named2 = filterAgents2 ?? [];
96114
+ if (named2.length === 1) return normalizeAgentType(named2[0]);
96115
+ if (named2.length > 1) return void 0;
96116
+ const sameEndpoint = existing2 !== null && normalizeEndpoint(existing2.endpoint) === endpoint;
96117
+ const held = sameEndpoint ? Object.keys(existing2?.agentTokens ?? {}) : [];
96118
+ return held.length === 1 ? held[0] : void 0;
96119
+ }
96120
+ async function assertNoLocalAgentReplacement(options2) {
96121
+ const existing2 = await loadLocalAgentConfig({ dryRun: true, envFallback: false });
96122
+ if (!existing2) return;
96123
+ const endpoint = normalizeEndpoint(options2.endpoint);
96124
+ if (existing2.endpoint !== endpoint) {
96125
+ throw new Error(
96126
+ `The HTTP local agent already uses ${existing2.endpoint}. Re-run with --force to replace it with ${endpoint}.`
96127
+ );
96128
+ }
96129
+ if (incomingTokenOwner(existing2, endpoint, options2.token, options2.filterAgents)) return;
96130
+ if (options2.token !== void 0 && existing2.token !== options2.token) {
96131
+ throw new Error(
96132
+ `The HTTP local agent already uses ${endpoint} with another token. Re-run with --force to replace the token.`
96133
+ );
96134
+ }
96135
+ }
96087
96136
  async function chooseAgentToken(existing2, agent, current2, incoming, spare) {
96088
96137
  if (!current2 || current2 === incoming) return incoming;
96089
96138
  if (await tokenStillWorks(existing2, current2) === false) {
@@ -96108,13 +96157,13 @@ async function initLocalAgentHttp(options2) {
96108
96157
  const token = options2.token?.trim() || void 0;
96109
96158
  const sameEndpoint = existing2 !== null && normalizeEndpoint(existing2.endpoint) === endpoint;
96110
96159
  const namedCount = options2.filterAgents?.length ?? 0;
96111
- const namedAgent = namedCount === 1 ? normalizeAgentType(options2.filterAgents[0]) : void 0;
96112
96160
  const held = sameEndpoint ? Object.keys(existing2?.agentTokens ?? {}) : [];
96113
- const agentScoped = token?.startsWith("sk-") === true;
96161
+ const agentScoped = isAgentToken(token);
96114
96162
  const inferred = namedCount === 0 && agentScoped && held.length === 1;
96115
- const agent = agentScoped ? namedAgent ?? (inferred ? held[0] : void 0) : void 0;
96163
+ const agent = agentScoped ? incomingTokenOwner(existing2, endpoint, token, options2.filterAgents) : void 0;
96116
96164
  const perAgent = Boolean(agent && token);
96117
- if (existing2 && configExisted && !options2.force && !(perAgent && sameEndpoint)) {
96165
+ const replaces = !sameEndpoint || token !== void 0 && token !== existing2?.token;
96166
+ if (existing2 && configExisted && !options2.force && replaces && !(perAgent && sameEndpoint)) {
96118
96167
  throw new Error("HTTP local agent is already initialized. Re-run with --force to overwrite.");
96119
96168
  }
96120
96169
  if (agentScoped && !agent && (namedCount > 1 || held.length > 1)) {
@@ -96144,6 +96193,7 @@ async function initLocalAgentHttp(options2) {
96144
96193
  }
96145
96194
  const config = {
96146
96195
  endpoint,
96196
+ // Never carry a token to another endpoint: a shared one stays only here.
96147
96197
  token: sharedToken,
96148
96198
  ...Object.keys(agentTokens).length > 0 ? { agentTokens } : {},
96149
96199
  createdAt: existing2?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
@@ -97441,6 +97491,10 @@ async function initHttp(url, options2) {
97441
97491
  log.info("Initializing teamai (HTTP read-only consumer)...");
97442
97492
  const requestedAgents = normalizeAgentList(options2.agent);
97443
97493
  warnAboutUncheckedHttpAgentIds(requestedAgents);
97494
+ const { assertNoLocalAgentReplacement: assertNoLocalAgentReplacement2, initLocalAgentHttp: initLocalAgentHttp2 } = await Promise.resolve().then(() => (init_local_agent(), local_agent_exports));
97495
+ if (!options2.force) {
97496
+ await assertNoLocalAgentReplacement2({ endpoint: url, token: options2.token, filterAgents: requestedAgents });
97497
+ }
97444
97498
  let scope;
97445
97499
  let projectRoot;
97446
97500
  let explicit;
@@ -97557,7 +97611,6 @@ async function initHttp(url, options2) {
97557
97611
  const filterAgents2 = requestedAgents.length > 0 ? requestedAgents : void 0;
97558
97612
  await runInitScript(localConfig2, "preInit", options2.dryRun);
97559
97613
  await reconcileHooksForInit(teamConfig, localConfig2, filterAgents2);
97560
- const { initLocalAgentHttp: initLocalAgentHttp2 } = await Promise.resolve().then(() => (init_local_agent(), local_agent_exports));
97561
97614
  let localAgentFailed = false;
97562
97615
  try {
97563
97616
  await initLocalAgentHttp2({ endpoint: url, token: options2.token, force: options2.force, filterAgents: filterAgents2 });
@@ -123302,7 +123355,12 @@ async function autoPushTeamRepo(repoPath, message) {
123302
123355
  await pushRepoDirectly(repoPath, message, ["."]);
123303
123356
  } catch (err) {
123304
123357
  DetachedTeamRepoError.rethrow(err);
123305
- log.warn(`[git] autoPush failed (non-blocking): ${err.message}`);
123358
+ const lines2 = err.message.split("\n").map((line) => line.trim()).filter(Boolean);
123359
+ const reasonLines = lines2.filter((line) => /^(error|fatal|remote):/.test(line) || /^!\s/.test(line) || /\[(remote )?rejected\]/.test(line));
123360
+ const reason = (reasonLines.length > 0 ? reasonLines : lines2.slice(0, 1)).join("\n") || "unknown error";
123361
+ const stale = /\(fetch first\)|\(non-fast-forward\)/.test(err.message);
123362
+ const advice = stale ? "\nRun `teamai pull`, then rerun this command." : "";
123363
+ throw new Error(`Push to the team repo failed: ${reason}${advice}`, { cause: err });
123306
123364
  }
123307
123365
  }
123308
123366
  async function autoPushViaMR(repoPath, message, files, teamConfig, localConfig2, opts = {}) {
@@ -124876,9 +124934,35 @@ function copilotRunsEntries(data) {
124876
124934
  function copilotCopyKey(event, matcher, command) {
124877
124935
  return createHash31("sha256").update(JSON.stringify([event, matcher && matcher !== "*" ? matcher : "", command])).digest("hex");
124878
124936
  }
124879
- function claudeHookOtherHostSkip(copilotEvent, copilotMatcher, command) {
124880
- if (!copilotEvent) return CURSOR_HOOK_SKIP;
124881
- return CURSOR_HOOK_SKIP + 'if [ -n "$COPILOT_PROJECT_DIR" ] && node -e ' + shellQuoteValue(PROJECT_COPILOT_COPY_CHECK) + ` "$COPILOT_PROJECT_DIR/.github/hooks" ${copilotCopyKey(copilotEvent, copilotMatcher, command)} 2>/dev/null; then exit 0; fi; `;
124937
+ function powershellQuoteValue(value) {
124938
+ return `'${value.replace(/'/g, "''")}'`;
124939
+ }
124940
+ function powershellProjectCopilotCopyCheck(event, matcher, command) {
124941
+ const expectedMatcher = matcher && matcher !== "*" ? matcher : "";
124942
+ return [
124943
+ '$teamaiHooks = Join-Path (Join-Path $env:COPILOT_PROJECT_DIR ".github") "hooks";',
124944
+ 'Get-ChildItem -LiteralPath $teamaiHooks -Filter "*.json" -File -ErrorAction SilentlyContinue | ForEach-Object {',
124945
+ "try { $teamaiFile = Get-Content -LiteralPath $_.FullName -Raw -Encoding UTF8 -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop } catch { return };",
124946
+ "$teamaiVersion = $teamaiFile.version;",
124947
+ "if ($null -eq $teamaiVersion -or $teamaiVersion -is [string] -or $teamaiVersion -is [bool] -or $teamaiVersion -ne 1 -or $teamaiFile.disableAllHooks -or $null -eq $teamaiFile.hooks -or $teamaiFile.hooks -is [array] -or $teamaiFile.hooks -is [string]) { return };",
124948
+ `$teamaiEntries = @($teamaiFile.hooks.PSObject.Properties | Where-Object { $_.Name -ceq ${powershellQuoteValue(event)} } | ForEach-Object { if ($_.Value -is [array]) { $_.Value } });`,
124949
+ "foreach ($teamaiEntry in $teamaiEntries) {",
124950
+ '$teamaiMatcher = if ($null -eq $teamaiEntry.matcher -or $teamaiEntry.matcher -ceq "*") { "" } else { [string]$teamaiEntry.matcher };',
124951
+ `$teamaiCommands = @($teamaiEntry.bash, $teamaiEntry.powershell, $teamaiEntry.command); if ($teamaiEntry.type -ceq "command" -and $teamaiMatcher -ceq ${powershellQuoteValue(expectedMatcher)} -and $teamaiCommands -ccontains ${powershellQuoteValue(command)}) { exit 0 }`,
124952
+ "}",
124953
+ "}; "
124954
+ ].join(" ");
124955
+ }
124956
+ function claudeHookUsesPowerShell(platform3 = process.platform, gitBashPath = platform3 === "win32" ? findGitBashWindows() : null) {
124957
+ return platform3 === "win32" && !gitBashPath;
124958
+ }
124959
+ function claudeHookOtherHostSkip(copilotEvent, copilotMatcher, command, platform3 = process.platform, gitBashPath = platform3 === "win32" ? findGitBashWindows() : null) {
124960
+ if (!claudeHookUsesPowerShell(platform3, gitBashPath)) {
124961
+ if (!copilotEvent) return CURSOR_HOOK_SKIP;
124962
+ return CURSOR_HOOK_SKIP + 'if [ -n "$COPILOT_PROJECT_DIR" ] && node -e ' + shellQuoteValue(PROJECT_COPILOT_COPY_CHECK) + ` "$COPILOT_PROJECT_DIR/.github/hooks" ${copilotCopyKey(copilotEvent, copilotMatcher, command)} 2>/dev/null; then exit 0; fi; `;
124963
+ }
124964
+ if (!copilotEvent) return POWERSHELL_CURSOR_HOOK_SKIP;
124965
+ return POWERSHELL_CURSOR_HOOK_SKIP + "if ($env:COPILOT_PROJECT_DIR) { " + powershellProjectCopilotCopyCheck(copilotEvent, copilotMatcher, command) + "}; ";
124882
124966
  }
124883
124967
  function homeDir(env3) {
124884
124968
  const home = env3.HOME?.trim() || env3.USERPROFILE?.trim();
@@ -124925,11 +125009,12 @@ function claudeHookRunsInAnotherHost(tool, env3 = process.env, includeGlobalCopi
124925
125009
  if (env3.COPILOT_PROJECT_DIR && copilotCopyInstalled(env3, includeGlobalCopilot)) return true;
124926
125010
  return false;
124927
125011
  }
124928
- var CURSOR_MARKER, COPILOT_MARKER, COPILOT_RUNS_ENTRIES_SOURCE, PROJECT_COPILOT_COPY_CHECK, CURSOR_HOOK_SKIP, LEGACY_CLAUDE_HOOK_OTHER_HOST_SKIP;
125012
+ var CURSOR_MARKER, COPILOT_MARKER, COPILOT_RUNS_ENTRIES_SOURCE, PROJECT_COPILOT_COPY_CHECK, POWERSHELL_CURSOR_HOOK_SKIP, CURSOR_HOOK_SKIP, LEGACY_POSIX_CLAUDE_HOOK_OTHER_HOST_SKIP, LEGACY_CLAUDE_HOOK_OTHER_HOST_SKIP;
124929
125013
  var init_claude_hook_host = __esm({
124930
125014
  "src/claude-hook-host.ts"() {
124931
125015
  "use strict";
124932
125016
  init_shell_profile();
125017
+ init_bundled_runtime();
124933
125018
  CURSOR_MARKER = "--tool cursor";
124934
125019
  COPILOT_MARKER = "--tool copilot";
124935
125020
  COPILOT_RUNS_ENTRIES_SOURCE = [
@@ -124950,8 +125035,10 @@ var init_claude_hook_host = __esm({
124950
125035
  ".some(([event, matcher, command]) => key(event, matcher, command) === process.argv[2]);",
124951
125036
  "} catch { return false; } }) ? 0 : 1); } catch { process.exit(1); }"
124952
125037
  ].join(" ");
125038
+ POWERSHELL_CURSOR_HOOK_SKIP = 'if ($env:CURSOR_VERSION) { $teamaiHome = if ($env:HOME) { $env:HOME } else { $env:USERPROFILE }; $files = @(); if ($teamaiHome) { $files += Join-Path (Join-Path $teamaiHome ".cursor") "hooks.json" }; if ($env:CURSOR_PROJECT_DIR) { $files += Join-Path (Join-Path $env:CURSOR_PROJECT_DIR ".cursor") "hooks.json" }; foreach ($file in $files) { if (Select-String -LiteralPath $file -SimpleMatch "--tool cursor" -Quiet -ErrorAction SilentlyContinue) { exit 0 } } }; ';
124953
125039
  CURSOR_HOOK_SKIP = `if [ -n "$CURSOR_VERSION" ] && { home="\${HOME:-$USERPROFILE}"; [ -n "$home" ] && { grep -q -- '--tool cursor' "$home/.cursor/hooks.json" 2>/dev/null || { [ -n "$CURSOR_PROJECT_DIR" ] && grep -q -- '--tool cursor' "$CURSOR_PROJECT_DIR/.cursor/hooks.json" 2>/dev/null; }; }; }; then exit 0; fi; `;
124954
- LEGACY_CLAUDE_HOOK_OTHER_HOST_SKIP = CURSOR_HOOK_SKIP + `if [ -n "$COPILOT_PROJECT_DIR" ] && grep -q -- '--tool copilot' "$COPILOT_PROJECT_DIR/.github/hooks/teamai.json" 2>/dev/null; then exit 0; fi; `;
125040
+ LEGACY_POSIX_CLAUDE_HOOK_OTHER_HOST_SKIP = CURSOR_HOOK_SKIP + `if [ -n "$COPILOT_PROJECT_DIR" ] && grep -q -- '--tool copilot' "$COPILOT_PROJECT_DIR/.github/hooks/teamai.json" 2>/dev/null; then exit 0; fi; `;
125041
+ LEGACY_CLAUDE_HOOK_OTHER_HOST_SKIP = LEGACY_POSIX_CLAUDE_HOOK_OTHER_HOST_SKIP;
124955
125042
  }
124956
125043
  });
124957
125044
 
@@ -125835,6 +125922,23 @@ async function migrateLegacyManagedHooks(localConfig2) {
125835
125922
  function shellQuote2(value) {
125836
125923
  return `'${value.replace(/'/g, `'"'"'`)}'`;
125837
125924
  }
125925
+ function powershellQuote(value) {
125926
+ return `'${value.replace(/'/g, "''")}'`;
125927
+ }
125928
+ function powershellPathPrefix(root) {
125929
+ return /[\\/]$/.test(root) ? root : `${root}\\`;
125930
+ }
125931
+ function powershellPathCondition(root) {
125932
+ const quoted2 = powershellQuote(root);
125933
+ const prefix = powershellQuote(powershellPathPrefix(root));
125934
+ return `($teamaiPwd.Equals(${quoted2}, [StringComparison]::OrdinalIgnoreCase) -or $teamaiPwd.StartsWith(${prefix}, [StringComparison]::OrdinalIgnoreCase))`;
125935
+ }
125936
+ function powershellProjectGate(command, projectRoot, childRoots) {
125937
+ const rootCondition = powershellPathCondition(projectRoot);
125938
+ const childCondition = childRoots.map((child) => powershellPathCondition(canonicalProjectRoot(child))).map((condition) => `-not (${condition})`).join(" -and ");
125939
+ const run3 = childCondition ? `if (${childCondition}) { ${command} }` : command;
125940
+ return `$teamaiPwd = $PWD.Path; if (${rootCondition}) { ${run3} }`;
125941
+ }
125838
125942
  function canonicalProjectRoot(projectRoot) {
125839
125943
  try {
125840
125944
  return realpathSync6.native(projectRoot);
@@ -125854,9 +125958,10 @@ function cmdProjectGate(root) {
125854
125958
  const literal = cmdLiteral(root.replace(/[\\/]+$/, ""));
125855
125959
  return `cd| findstr /i /b /l /c:${literal}\\\\ >nul || cd| findstr /i /e /l /c:${literal} >nul`;
125856
125960
  }
125857
- function gateTeamHookCommand(command, projectRoot, childRoots = []) {
125961
+ function gateTeamHookCommand(command, projectRoot, childRoots = [], shell) {
125858
125962
  if (!projectRoot) return command;
125859
125963
  const root = canonicalProjectRoot(projectRoot);
125964
+ if (shell === "powershell") return powershellProjectGate(command, root, childRoots);
125860
125965
  const msys = msysProjectRoot(root);
125861
125966
  const quoted2 = shellQuote2(root);
125862
125967
  const childPatterns = childRoots.flatMap((child) => {
@@ -125874,6 +125979,20 @@ function gateTeamHookCommand(command, projectRoot, childRoots = []) {
125874
125979
  function regateTeamHookCommand(command, projectRoot, childRoots) {
125875
125980
  const codebuddy = regateCodebuddyTeamHookCommand(command, projectRoot, childRoots);
125876
125981
  if (codebuddy !== null) return codebuddy;
125982
+ const powershellPrefix = "$teamaiPwd = $PWD.Path; if (";
125983
+ const powershellSuffix = " }";
125984
+ if (command.startsWith(powershellPrefix) && command.endsWith(powershellSuffix)) {
125985
+ const bodyStart = command.indexOf(") { ", powershellPrefix.length);
125986
+ if (bodyStart >= 0) {
125987
+ let payload2 = command.slice(bodyStart + 4, -powershellSuffix.length);
125988
+ const childPrefix = "if (-not (";
125989
+ if (payload2.startsWith(childPrefix)) {
125990
+ const childBody = payload2.indexOf(") { ");
125991
+ if (childBody >= 0 && payload2.endsWith(" }")) payload2 = payload2.slice(childBody + 4, -2);
125992
+ }
125993
+ return gateTeamHookCommand(payload2, projectRoot, childRoots, "powershell");
125994
+ }
125995
+ }
125877
125996
  const [head, tail] = gateTeamHookCommand("\0", projectRoot).split("(\0)");
125878
125997
  if (!command.startsWith(head) || !command.endsWith(tail)) return null;
125879
125998
  const run3 = command.slice(head.length, command.length - tail.length);
@@ -125925,10 +126044,11 @@ function heldEntryCheck(tool, held, found, byMarker) {
125925
126044
  }
125926
126045
  function isGatedForProject(command, projectRoot) {
125927
126046
  const root = canonicalProjectRoot(projectRoot);
125928
- return isCodebuddyTeamGateForProject(command, root) || command.startsWith(`if [ "$PWD" = ${shellQuote2(root)} ]`) || command.startsWith(cmdProjectGate(root));
126047
+ const powershellPrefix = powershellProjectGate("\0", root, []).split("\0")[0];
126048
+ return isCodebuddyTeamGateForProject(command, root) || command.startsWith(powershellPrefix) || command.startsWith(`if [ "$PWD" = ${shellQuote2(root)} ]`) || command.startsWith(cmdProjectGate(root));
125929
126049
  }
125930
126050
  function isProjectGatedCommand(command) {
125931
- return parseCodebuddyTeamGate(command) !== null || command.startsWith('if [ "$PWD" = ') || command.startsWith("cd| findstr ");
126051
+ return parseCodebuddyTeamGate(command) !== null || command.startsWith("$teamaiPwd = $PWD.Path; if (") || command.startsWith('if [ "$PWD" = ') || command.startsWith("cd| findstr ");
125932
126052
  }
125933
126053
  function skipWhenAnotherHostLoadsClaudeSettings(def, tool, legacyGuard = false) {
125934
126054
  if (tool !== "claude") return def.command;
@@ -126265,7 +126385,8 @@ async function staleCheckoutGateRoots(manifestPath2, tool, current2, mainCheckou
126265
126385
  function scopedTeamDefs(teamDefs, projectRoot, tool, legacyGuard = false, childRoots = [], codebuddyDualRunner = false) {
126266
126386
  const prepared = teamDefs.map((def) => ({
126267
126387
  ...def,
126268
- command: skipWhenAnotherHostLoadsClaudeSettings(def, tool, legacyGuard)
126388
+ command: skipWhenAnotherHostLoadsClaudeSettings(def, tool, legacyGuard),
126389
+ ...tool === "claude" && def.source === "team" && process.platform === "win32" && !legacyGuard && claudeHookUsesPowerShell() ? { shell: "powershell" } : {}
126269
126390
  }));
126270
126391
  if (!projectRoot) return prepared;
126271
126392
  if (tool === "codebuddy" && process.platform === "win32" && codebuddyDualRunner) {
@@ -126281,7 +126402,7 @@ function scopedTeamDefs(teamDefs, projectRoot, tool, legacyGuard = false, childR
126281
126402
  )
126282
126403
  }));
126283
126404
  }
126284
- return prepared.map((def) => ({ ...def, command: gateTeamHookCommand(def.command, projectRoot, childRoots) }));
126405
+ return prepared.map((def) => ({ ...def, command: gateTeamHookCommand(def.command, projectRoot, childRoots, def.shell) }));
126285
126406
  }
126286
126407
  function manifestRecordsForTool(teamDefs, tool, removeAll, projectRoot, childRoots = [], codebuddyDualRunner = false) {
126287
126408
  if (removeAll) return [];
@@ -126299,6 +126420,7 @@ function toClaudeEntry(def) {
126299
126420
  {
126300
126421
  type: "command",
126301
126422
  command: def.command,
126423
+ ...def.shell ? { shell: def.shell } : {},
126302
126424
  ...def.timeout !== void 0 ? { timeout: def.timeout } : {}
126303
126425
  }
126304
126426
  ],
@@ -133777,11 +133899,11 @@ function parseLease(raw) {
133777
133899
  const bare = LeaseWireSchema.safeParse({ ...raw, workspace: void 0 });
133778
133900
  return bare.success ? { ...bare.data, unreadableWorkspace: true } : void 0;
133779
133901
  }
133780
- async function stageLease(lease2, { config, lock, root, values, mode, signal }) {
133902
+ async function stageLease(lease2, { config, lock, root, env: env3, mode, signal }) {
133781
133903
  if (lease2.unreadableWorkspace) return unreadablePlace(lock.run);
133782
133904
  await stopRecordedGroup(attemptDir(config, lock.run, lease2.attempt));
133783
133905
  if (lease2.envScope) {
133784
- const scoped = await stepEnvironment(values, lease2.envScope);
133906
+ const scoped = await stepEnvironment(env3, lease2.envScope);
133785
133907
  if (!scoped.ok) return scoped.failure;
133786
133908
  lease2.processEnv = scoped.env;
133787
133909
  }
@@ -133789,7 +133911,7 @@ async function stageLease(lease2, { config, lock, root, values, mode, signal })
133789
133911
  if (prepared.kind !== "prepared") return prepared.failure;
133790
133912
  lease2.cwd = prepared.dir;
133791
133913
  if (prepared.prompt !== void 0) lease2.prompt = prepared.prompt;
133792
- return runPlaceSetup({ config, run: lock.run, attempt: lease2.attempt, mode, values, ...signal ? { signal } : {} });
133914
+ return runPlaceSetup({ config, run: lock.run, attempt: lease2.attempt, mode, env: env3, ...signal ? { signal } : {} });
133793
133915
  }
133794
133916
  async function resumeSession(archive, lease2, tool, cwd) {
133795
133917
  const to = AgentSession.platformForTool(tool);
@@ -134085,7 +134207,7 @@ async function driveRun(config, lock, cwd, options2) {
134085
134207
  if (forwarded) handle(STOP_SIGNALS);
134086
134208
  inFlight2.set(lease2.attempt, { lease: lease2, command: stageThenStart(
134087
134209
  lease2,
134088
- (signal) => stageLease(lease2, { config, lock, root, values: turn.values, mode, signal }),
134210
+ (signal) => stageLease(lease2, { config, lock, root, env: turn, mode, signal }),
134089
134211
  () => {
134090
134212
  if (forwarded) handle(forwarded);
134091
134213
  return startGroupedCommand({
@@ -134112,7 +134234,7 @@ async function driveRun(config, lock, cwd, options2) {
134112
134234
  const controller = new AbortController();
134113
134235
  if (maxParallel === 1) handle(STOP_SIGNALS);
134114
134236
  prompt = { lease: lease2, controller, exit: (async () => {
134115
- const failure3 = await stageLease(lease2, { config, lock, root, values: turn.values, mode, signal: controller.signal });
134237
+ const failure3 = await stageLease(lease2, { config, lock, root, env: turn, mode, signal: controller.signal });
134116
134238
  if (!startable(lease2, controller.signal)) {
134117
134239
  await abandonPlace({ config, lock, attempt: lease2.attempt });
134118
134240
  return void 0;
@@ -148279,14 +148401,17 @@ async function readFileSafe2(filePath) {
148279
148401
  return "";
148280
148402
  }
148281
148403
  }
148404
+ function symlinkRefusal(linkPath) {
148405
+ return new Error(`Cannot deep-enrich through a symbolic link: ${linkPath}. Replace it with a regular file or directory before retrying.`);
148406
+ }
148282
148407
  async function assertSafeOutputDir(dir) {
148283
148408
  try {
148284
148409
  if ((await lstat5(dir)).isSymbolicLink()) {
148285
- throw new Error(`Cannot deep-enrich through a symbolic link: ${dir}`);
148410
+ throw symlinkRefusal(dir);
148286
148411
  }
148287
148412
  for (const entry of await readdir6(dir, { withFileTypes: true })) {
148288
148413
  if (entry.isSymbolicLink()) {
148289
- throw new Error(`Cannot deep-enrich through a symbolic link: ${path237.join(dir, entry.name)}`);
148414
+ throw symlinkRefusal(path237.join(dir, entry.name));
148290
148415
  }
148291
148416
  }
148292
148417
  } catch (error2) {
@@ -148298,7 +148423,7 @@ async function assertSafeEvidencePath(wikiRoot, evidenceDir2) {
148298
148423
  const root = path237.resolve(wikiRoot);
148299
148424
  for (let dir = path237.resolve(evidenceDir2); ; dir = path237.dirname(dir)) {
148300
148425
  if ((await lstat5(dir)).isSymbolicLink()) {
148301
- throw new Error(`Cannot deep-enrich through a symbolic link: ${dir}`);
148426
+ throw symlinkRefusal(dir);
148302
148427
  }
148303
148428
  if (dir === root) break;
148304
148429
  }
@@ -149211,6 +149336,7 @@ var init_rebuild_wiki_index = __esm({
149211
149336
  // src/import-codebase.ts
149212
149337
  var import_codebase_exports = {};
149213
149338
  __export(import_codebase_exports, {
149339
+ failIncompleteDeepEnrich: () => failIncompleteDeepEnrich,
149214
149340
  importCodebase: () => importCodebase,
149215
149341
  importLocalCheckout: () => importLocalCheckout,
149216
149342
  localCheckoutSlug: () => localCheckoutSlug,
@@ -149518,16 +149644,26 @@ async function reconcileAndDeepEnrich(params) {
149518
149644
  log.debug(`reconcile skipped: ${err.message}`);
149519
149645
  }
149520
149646
  const evidenceDir2 = path239.join(wikiRoot, "evidence", "code", slug);
149521
- if (skipEnrich || !await import_fs_extra19.default.pathExists(path239.join(evidenceDir2, "_manifest.json"))) return;
149647
+ if (skipEnrich || !await import_fs_extra19.default.pathExists(path239.join(evidenceDir2, "_manifest.json"))) return true;
149522
149648
  try {
149523
149649
  const { deepEnrich: deepEnrich2 } = await Promise.resolve().then(() => (init_deep_enrich(), deep_enrich_exports));
149524
- await deepEnrich2({ project: slug, evidenceDir: evidenceDir2, wikiRoot, cacheDir: sourceDir });
149525
- log.info(`Deep enrich complete: ${slug}`);
149650
+ const result = await deepEnrich2({ project: slug, evidenceDir: evidenceDir2, wikiRoot, cacheDir: sourceDir });
149651
+ if (result.complete) log.info(`Deep enrich complete: ${slug}`);
149652
+ return result.complete;
149526
149653
  } catch (err) {
149527
149654
  if (isOverrideInvalid(err)) throw err;
149528
- log.debug(`deep-enrich failed for ${slug} (non-blocking): ${err.message}`);
149655
+ log.warn(`Deep enrich failed for ${slug}: ${err instanceof Error ? err.message : String(err)}`);
149656
+ return false;
149529
149657
  }
149530
149658
  }
149659
+ function failIncompleteDeepEnrich({ slug, output, importArgs }) {
149660
+ const retry = output ? `teamai codebase --deep-enrich --project ${slug} --output ${shellArg(output)}` : `teamai import ${importArgs.map(shellArg).join(" ")}`;
149661
+ log.warn(`Deep enrich incomplete: ${slug}. Run \`${retry}\` to retry.`);
149662
+ process.exitCode = 1;
149663
+ }
149664
+ function shellArg(value) {
149665
+ return /^[\w@%+=:,./-]+$/.test(value) ? value : shellQuoteValue(value);
149666
+ }
149531
149667
  async function refreshTeamwikiIndexes(wikiRoot) {
149532
149668
  try {
149533
149669
  const { aggregateGlobalGraph: aggregateGlobalGraph2 } = await Promise.resolve().then(() => (init_graph_aggregate(), graph_aggregate_exports));
@@ -149559,17 +149695,17 @@ async function importLocalCheckout(opts) {
149559
149695
  const updated = await importCodebase(opts);
149560
149696
  if (!updated) {
149561
149697
  log.info(`${opts.slug}: no source changes since the last import, teamwiki unchanged`);
149562
- return false;
149698
+ return { updated: false };
149563
149699
  }
149564
149700
  log.info(`teamwiki/ knowledge graph updated: ${opts.slug}`);
149565
- await reconcileAndDeepEnrich({
149701
+ const deepEnrichComplete = await reconcileAndDeepEnrich({
149566
149702
  slug: opts.slug,
149567
149703
  wikiRoot: opts.wikiRoot,
149568
149704
  sourceDir: opts.sourceDir,
149569
149705
  skipEnrich: opts.skipEnrich ?? false
149570
149706
  });
149571
149707
  await refreshTeamwikiIndexes(opts.wikiRoot);
149572
- return true;
149708
+ return { updated: true, deepEnrichComplete };
149573
149709
  }
149574
149710
  var import_fs_extra19, INCREMENTAL_CACHES, CodebaseManifestSchema, PROVIDER_SLUG_PREFIXES, CodebaseSourceSchema;
149575
149711
  var init_import_codebase = __esm({
@@ -149581,6 +149717,7 @@ var init_import_codebase = __esm({
149581
149717
  init_logger();
149582
149718
  init_git2();
149583
149719
  init_path_safety();
149720
+ init_shell_profile();
149584
149721
  init_call();
149585
149722
  INCREMENTAL_CACHES = ["facts-cache.json", "interfaces-cache.json"];
149586
149723
  CodebaseManifestSchema = external_exports.object({
@@ -150315,7 +150452,7 @@ async function importFromRepo(opts) {
150315
150452
  const skips = previewIncremental && await publishedHead() === head;
150316
150453
  const cache = !cacheExists ? `not cached yet, a real run would clone it into ${cacheDir3}` : lastSync?.sha === head ? `cache is current at ${head.slice(0, 8)}${skips ? ", so an incremental run would skip it" : ""}` : `cache would be refreshed from ${lastSync ? lastSync.sha.slice(0, 8) : "an unrecorded commit"} to ${head.slice(0, 8)}`;
150317
150454
  log.info(`[dry-run] Would import ${owner}/${repoName2} at ${head.slice(0, 8)} into ${evidenceDest ?? path242.join("teamwiki", "evidence", "code", slug)}; ${cache}`);
150318
- return;
150455
+ return true;
150319
150456
  }
150320
150457
  if (!target || !evidenceDest) throw new Error("unreachable: the teamwiki resolves outside a dry run");
150321
150458
  const { wikiRoot: teamwikiRoot, team } = target;
@@ -150371,7 +150508,7 @@ async function importFromRepo(opts) {
150371
150508
  } catch {
150372
150509
  }
150373
150510
  log.info(source_default.green(`\u2713 repo ${owner}/${repoName2} unchanged, skipped`));
150374
- return;
150511
+ return true;
150375
150512
  }
150376
150513
  log.info(`Scanning repository...`);
150377
150514
  let codebaseMd;
@@ -150441,8 +150578,9 @@ ${aiNarrative}`;
150441
150578
  } catch (err) {
150442
150579
  throw new Error(`Knowledge extraction failed: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
150443
150580
  }
150581
+ let deepEnrichComplete = true;
150444
150582
  if (updated) {
150445
- await reconcileAndDeepEnrich({ slug, wikiRoot: teamwikiRoot, sourceDir: cacheDir3, skipEnrich });
150583
+ deepEnrichComplete = await reconcileAndDeepEnrich({ slug, wikiRoot: teamwikiRoot, sourceDir: cacheDir3, skipEnrich });
150446
150584
  if (!skipAutoPush) {
150447
150585
  await refreshTeamwikiIndexes(teamwikiRoot);
150448
150586
  if (team) await publishTeamwikiViaMR(team, `[teamai] Import codebase knowledge from ${owner}/${repoName2}`);
@@ -150455,6 +150593,7 @@ ${aiNarrative}`;
150455
150593
  } catch (touchErr) {
150456
150594
  log.debug(`[cache-index] touchCacheEntry failed: ${String(touchErr)}`);
150457
150595
  }
150596
+ return deepEnrichComplete;
150458
150597
  } finally {
150459
150598
  await releaseImportLock();
150460
150599
  }
@@ -151316,11 +151455,14 @@ var init_codebase_freshness = __esm({
151316
151455
  // src/recall.ts
151317
151456
  var recall_exports = {};
151318
151457
  __export(recall_exports, {
151458
+ LEARNINGS_ABSOLUTE_FLOOR: () => LEARNINGS_ABSOLUTE_FLOOR,
151459
+ LEARNINGS_RELEVANCE_RATIO: () => LEARNINGS_RELEVANCE_RATIO,
151319
151460
  autoUpvote: () => autoUpvote,
151320
151461
  computeIdfBaseline: () => computeIdfBaseline,
151321
151462
  formatResults: () => formatResults,
151322
151463
  isRelevantScore: () => isRelevantScore,
151323
151464
  normalizeLearningsScoreForRanking: () => normalizeLearningsScoreForRanking,
151465
+ rankingScoreOf: () => rankingScoreOf,
151324
151466
  recall: () => recall
151325
151467
  });
151326
151468
  import { randomUUID as randomUUID16 } from "crypto";
@@ -151356,6 +151498,9 @@ function normalizeLearningsScoreForRanking(score2, idfBaseline) {
151356
151498
  const threshold = Math.max(baseline * LEARNINGS_RELEVANCE_RATIO, LEARNINGS_ABSOLUTE_FLOOR);
151357
151499
  return Math.min(10, Math.max(0, 4 + 2 * Math.log2(score2 / threshold)));
151358
151500
  }
151501
+ function rankingScoreOf(result, idfBaseline) {
151502
+ return result.fromCodebase ? result.score * CODE_HIT_RANKING_PENALTY : normalizeLearningsScoreForRanking(result.score, result.idfBaseline ?? idfBaseline);
151503
+ }
151359
151504
  function resolveReadablePath(indexedPath, filename, learningsBase) {
151360
151505
  if (indexedPath && existsSync10(indexedPath)) return indexedPath;
151361
151506
  const underBase = learningsBase ? path246.join(learningsBase, filename) : null;
@@ -151725,8 +151870,11 @@ async function recall(query, options2) {
151725
151870
  } catch {
151726
151871
  log.warn("recall: code graph retrieval unavailable, run teamai codebase --lint to diagnose");
151727
151872
  }
151728
- const rankingScore = (result) => result.fromCodebase ? result.score : normalizeLearningsScoreForRanking(result.score, result.idfBaseline ?? idfBaseline);
151873
+ const rankingScore = (result) => rankingScoreOf(result, idfBaseline);
151874
+ const relevant = (result) => isRelevantScore(result.score, result.fromCodebase ?? false, result.idfBaseline ?? idfBaseline);
151729
151875
  allResults.sort((a, b2) => {
151876
+ const relevanceDelta = Number(relevant(b2)) - Number(relevant(a));
151877
+ if (relevanceDelta !== 0) return relevanceDelta;
151730
151878
  const scoreDelta = rankingScore(b2) - rankingScore(a);
151731
151879
  if (scoreDelta !== 0) return scoreDelta;
151732
151880
  return (b2.entry.date || "").localeCompare(a.entry.date || "");
@@ -151773,7 +151921,7 @@ async function recall(query, options2) {
151773
151921
  }
151774
151922
  }
151775
151923
  }
151776
- var CODEBASE_RELEVANCE_THRESHOLD, LEARNINGS_RELEVANCE_RATIO, LEARNINGS_ABSOLUTE_FLOOR;
151924
+ var CODEBASE_RELEVANCE_THRESHOLD, CODE_HIT_RANKING_PENALTY, LEARNINGS_RELEVANCE_RATIO, LEARNINGS_ABSOLUTE_FLOOR;
151777
151925
  var init_recall = __esm({
151778
151926
  "src/recall.ts"() {
151779
151927
  "use strict";
@@ -151789,6 +151937,7 @@ var init_recall = __esm({
151789
151937
  init_recall_quality();
151790
151938
  init_session_id();
151791
151939
  CODEBASE_RELEVANCE_THRESHOLD = 4;
151940
+ CODE_HIT_RANKING_PENALTY = 0.8;
151792
151941
  LEARNINGS_RELEVANCE_RATIO = 1.35;
151793
151942
  LEARNINGS_ABSOLUTE_FLOOR = 4;
151794
151943
  }
@@ -153650,7 +153799,7 @@ async function importFromRepoList(opts) {
153650
153799
  const isPublic = entry.auth === "public";
153651
153800
  const entryForceSsh = entry.auth === "ssh" || forceSsh;
153652
153801
  try {
153653
- await importFromRepo({
153802
+ const deepEnrichComplete = await importFromRepo({
153654
153803
  url: entry.url,
153655
153804
  forceSsh: entryForceSsh,
153656
153805
  forceAnonymous: isPublic,
@@ -153662,6 +153811,19 @@ async function importFromRepoList(opts) {
153662
153811
  skipEnrich,
153663
153812
  maxFiles
153664
153813
  });
153814
+ if (!deepEnrichComplete) {
153815
+ failIncompleteDeepEnrich({
153816
+ slug: repoSlugForUrl(entry.url),
153817
+ output,
153818
+ importArgs: [
153819
+ "--from-repo",
153820
+ entry.url,
153821
+ ...entryForceSsh ? ["--ssh"] : [],
153822
+ ...entry.domain ? ["--domain", entry.domain] : [],
153823
+ ...maxFiles !== void 0 ? ["--max-files", String(maxFiles)] : []
153824
+ ]
153825
+ });
153826
+ }
153665
153827
  succeeded.push(1);
153666
153828
  } catch (err) {
153667
153829
  const message = err instanceof Error ? err.message : String(err);
@@ -158566,13 +158728,15 @@ async function importCmd(opts) {
158566
158728
  await tasks.run();
158567
158729
  return;
158568
158730
  } else if (opts.fromRepo) {
158731
+ const fromRepo = opts.fromRepo;
158732
+ let deepEnrichComplete = true;
158569
158733
  const tasks = new Listr2([
158570
158734
  {
158571
158735
  title: "Import remote repository",
158572
158736
  task: async (ctx, task) => {
158573
- task.output = `Repository: ${opts.fromRepo}`;
158574
- await importFromRepo({
158575
- url: opts.fromRepo,
158737
+ task.output = `Repository: ${fromRepo}`;
158738
+ deepEnrichComplete = await importFromRepo({
158739
+ url: fromRepo,
158576
158740
  depth: opts.depth ? parseInt(opts.depth, 10) : 1,
158577
158741
  forceSsh: opts.ssh ?? false,
158578
158742
  explicitDomain: opts.domain,
@@ -158590,6 +158754,20 @@ async function importCmd(opts) {
158590
158754
  exitOnError: true
158591
158755
  });
158592
158756
  await tasks.run();
158757
+ if (!deepEnrichComplete) {
158758
+ const { failIncompleteDeepEnrich: failIncompleteDeepEnrich2 } = await Promise.resolve().then(() => (init_import_codebase(), import_codebase_exports));
158759
+ failIncompleteDeepEnrich2({
158760
+ slug: repoSlugForUrl(fromRepo),
158761
+ output: opts.output,
158762
+ importArgs: [
158763
+ "--from-repo",
158764
+ fromRepo,
158765
+ ...opts.ssh ? ["--ssh"] : [],
158766
+ ...opts.domain ? ["--domain", opts.domain] : [],
158767
+ ...opts.maxFiles ? ["--max-files", opts.maxFiles] : []
158768
+ ]
158769
+ });
158770
+ }
158593
158771
  return;
158594
158772
  } else if (opts.fromRepoList) {
158595
158773
  const tasks = new Listr2([
@@ -158723,7 +158901,6 @@ async function importCmd(opts) {
158723
158901
  skip: (ctx) => !ctx.items.some((item) => item.repoUrl) || !!opts.dryRun || !!opts.output,
158724
158902
  task: async (ctx, task) => {
158725
158903
  const teamwikiRoot = path256.join(localConfig2.repo.localPath, "teamwiki");
158726
- const { repoSlugForUrl: repoSlugForUrl2 } = await Promise.resolve().then(() => (init_import_repo(), import_repo_exports));
158727
158904
  const mrUrlsByRepo = /* @__PURE__ */ new Map();
158728
158905
  for (const item of ctx.items) {
158729
158906
  if (!item.repoUrl) continue;
@@ -158732,7 +158909,7 @@ async function importCmd(opts) {
158732
158909
  const skipped = [];
158733
158910
  for (const [repoUrl, sourceMrUrls] of mrUrlsByRepo) {
158734
158911
  try {
158735
- const slug = repoSlugForUrl2(repoUrl);
158912
+ const slug = repoSlugForUrl(repoUrl);
158736
158913
  const evidenceDir2 = path256.join(teamwikiRoot, "evidence", "code", slug);
158737
158914
  if (!await import_fs_extra30.default.pathExists(evidenceDir2)) {
158738
158915
  skipped.push(`No existing evidence for ${slug}`);
@@ -158807,7 +158984,12 @@ async function importCmd(opts) {
158807
158984
  const dirSlug = await defaultProjectSlug2(dirPath);
158808
158985
  const checkoutSlug = await checkoutName2(dirPath);
158809
158986
  const { lockTeamwiki: lockTeamwiki2, resolveTeamwiki: resolveTeamwiki2 } = await Promise.resolve().then(() => (init_teamwiki_root(), teamwiki_root_exports));
158810
- const { importLocalCheckout: importLocalCheckout2, localCheckoutSlug: localCheckoutSlug2, ownLegacySlug: ownLegacySlug2 } = await Promise.resolve().then(() => (init_import_codebase(), import_codebase_exports));
158987
+ const {
158988
+ failIncompleteDeepEnrich: failIncompleteDeepEnrich2,
158989
+ importLocalCheckout: importLocalCheckout2,
158990
+ localCheckoutSlug: localCheckoutSlug2,
158991
+ ownLegacySlug: ownLegacySlug2
158992
+ } = await Promise.resolve().then(() => (init_import_codebase(), import_codebase_exports));
158811
158993
  if (opts.dryRun) {
158812
158994
  const preview = await resolveTeamwiki2({ output: opts.output, dryRun: true }).catch(() => void 0);
158813
158995
  const slug = preview ? await localCheckoutSlug2({ sourceDir: dirPath, slug: dirSlug, wikiRoot: preview.wikiRoot }) : dirSlug;
@@ -158823,7 +159005,7 @@ async function importCmd(opts) {
158823
159005
  const slug = await localCheckoutSlug2({ sourceDir: dirPath, slug: dirSlug, wikiRoot });
158824
159006
  const legacySlug = slug === dirSlug && checkoutSlug !== slug ? await ownLegacySlug2({ sourceDir: dirPath, slug: checkoutSlug, wikiRoot }) : checkoutSlug;
158825
159007
  log.info(`Scanning local directory: ${dirPath} (project: ${slug})`);
158826
- const updated = await importLocalCheckout2({
159008
+ const imported = await importLocalCheckout2({
158827
159009
  sourceDir: dirPath,
158828
159010
  slug,
158829
159011
  // A suffixed slug is a new codebase; the directory-named evidence is another source's.
@@ -158838,11 +159020,18 @@ async function importCmd(opts) {
158838
159020
  }
158839
159021
  if (!team) {
158840
159022
  log.info(`Output written: ${wikiRoot}`);
158841
- } else if (updated) {
159023
+ } else if (imported.updated) {
158842
159024
  await autoPushTeamRepo(team.localConfig.repo.localPath, `[teamai] Import from local dir: ${slug}`);
158843
159025
  log.success(`Pushed to team knowledge repo (${team.localConfig.repo.remote})`);
158844
159026
  }
158845
159027
  log.success(`Local directory ${slug} import complete`);
159028
+ if (imported.updated && !imported.deepEnrichComplete) {
159029
+ failIncompleteDeepEnrich2({
159030
+ slug,
159031
+ output: opts.output,
159032
+ importArgs: ["--dir", opts.dir, ...opts.maxFiles ? ["--max-files", opts.maxFiles] : []]
159033
+ });
159034
+ }
158846
159035
  } finally {
158847
159036
  await releaseImportLock();
158848
159037
  }
@@ -158859,10 +159048,10 @@ async function importCmd(opts) {
158859
159048
  dryRun: opts.dryRun,
158860
159049
  outputDir: opts.output
158861
159050
  });
158862
- log.success("Import complete");
158863
159051
  if (pushed > 0 && !opts.dryRun && !opts.output) {
158864
159052
  await autoPushTeamRepo(localConfig2.repo.localPath, `[teamai] Import from local: claude-rules`);
158865
159053
  }
159054
+ log.success("Import complete");
158866
159055
  } else {
158867
159056
  log.info("Please specify import source: --dir <path>, --from-repo <url>, --from-repo-list <yaml>, --from-org <org>, --from-mr <url>, or --from-iwiki <id>");
158868
159057
  return;
@@ -161549,7 +161738,7 @@ async function importMergedCheckout(teamRepo, repoUrl, mrUrl) {
161549
161738
  try {
161550
161739
  const { repoSlugForUrl: repoSlugForUrl2 } = await Promise.resolve().then(() => (init_import_repo(), import_repo_exports));
161551
161740
  const { importLocalCheckout: importLocalCheckout2 } = await Promise.resolve().then(() => (init_import_codebase(), import_codebase_exports));
161552
- return await importLocalCheckout2({
161741
+ const { updated } = await importLocalCheckout2({
161553
161742
  sourceDir,
161554
161743
  slug: repoSlugForUrl2(repoUrl),
161555
161744
  wikiRoot: path262.join(teamRepoDir, "teamwiki"),
@@ -161557,6 +161746,7 @@ async function importMergedCheckout(teamRepo, repoUrl, mrUrl) {
161557
161746
  repoUrl,
161558
161747
  sourceMrUrl: mrUrl
161559
161748
  });
161749
+ return updated;
161560
161750
  } catch (err) {
161561
161751
  log.warn(`teamwiki update failed (non-blocking): ${err instanceof Error ? err.message : String(err)}`);
161562
161752
  return false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@team-ai/teamai-cli",
3
- "version": "0.40.8",
3
+ "version": "0.40.9",
4
4
  "description": "TeamAI — Make Every Team AI Native (skill sync + shared knowledge base, powered by Git)",
5
5
  "type": "module",
6
6
  "bin": {