@carrieros/cli 0.2.0 → 0.4.0

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 (124) hide show
  1. package/README.md +170 -64
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/btw.js +78 -0
  4. package/dist/commands/changes.js +167 -0
  5. package/dist/commands/chat.js +81 -15
  6. package/dist/commands/context.js +200 -0
  7. package/dist/commands/doctor.js +63 -3
  8. package/dist/commands/files.js +84 -23
  9. package/dist/commands/help.js +1 -0
  10. package/dist/commands/history.js +88 -23
  11. package/dist/commands/login.js +31 -7
  12. package/dist/commands/logout.js +1 -0
  13. package/dist/commands/memory.js +162 -0
  14. package/dist/commands/mode-model.js +39 -3
  15. package/dist/commands/modes.js +4 -1
  16. package/dist/commands/permissions.js +77 -0
  17. package/dist/commands/project.js +106 -0
  18. package/dist/commands/repo.js +146 -0
  19. package/dist/commands/repos.js +61 -0
  20. package/dist/commands/review.js +92 -0
  21. package/dist/commands/scope.js +9 -6
  22. package/dist/commands/search.js +92 -0
  23. package/dist/commands/sessions.js +224 -65
  24. package/dist/commands/settings.js +94 -0
  25. package/dist/commands/update.js +229 -0
  26. package/dist/commands/upload.js +204 -31
  27. package/dist/commands/usage.js +213 -17
  28. package/dist/commands/whoami.js +12 -9
  29. package/dist/ide/editor-context.js +275 -0
  30. package/dist/ide/ide-session.js +355 -0
  31. package/dist/ide/tool-host.js +109 -0
  32. package/dist/main.js +26 -1
  33. package/dist/services/api.js +315 -15
  34. package/dist/services/auth-origin.js +20 -0
  35. package/dist/services/chat-stream.js +168 -0
  36. package/dist/services/checkpoints.js +278 -0
  37. package/dist/services/client-tools.js +352 -0
  38. package/dist/services/code-intel.js +243 -0
  39. package/dist/services/code-symbols.js +94 -0
  40. package/dist/services/coding-workflow.js +554 -0
  41. package/dist/services/command-coordinator.js +273 -0
  42. package/dist/services/command-policy.js +434 -0
  43. package/dist/services/config.js +311 -24
  44. package/dist/services/container-runner.js +254 -0
  45. package/dist/services/container-supervisor.js +38 -0
  46. package/dist/services/context.js +296 -23
  47. package/dist/services/device-auth.js +72 -35
  48. package/dist/services/diff.js +196 -0
  49. package/dist/services/env-policy.js +108 -0
  50. package/dist/services/execution-platform.js +30 -0
  51. package/dist/services/file-detect.js +104 -0
  52. package/dist/services/file-resolver.js +199 -0
  53. package/dist/services/file-upload.js +126 -0
  54. package/dist/services/folder-key.js +22 -0
  55. package/dist/services/git-tools.js +429 -0
  56. package/dist/services/glob-match.js +164 -0
  57. package/dist/services/helper-bin.js +85 -0
  58. package/dist/services/ignore-rules.js +189 -0
  59. package/dist/services/instruction-resolver.js +54 -0
  60. package/dist/services/job-helper.js +328 -0
  61. package/dist/services/local-files.js +639 -0
  62. package/dist/services/local-tools.js +937 -0
  63. package/dist/services/login-flow.js +55 -17
  64. package/dist/services/meta.js +3 -1
  65. package/dist/services/mutation-coordinator.js +327 -0
  66. package/dist/services/mutation-groups.js +309 -0
  67. package/dist/services/mutation-recovery.js +159 -0
  68. package/dist/services/mutations.js +679 -0
  69. package/dist/services/open-url.js +68 -0
  70. package/dist/services/output.js +5 -2
  71. package/dist/services/packaged-update.js +403 -0
  72. package/dist/services/packaged.js +39 -0
  73. package/dist/services/permission-mode.js +60 -0
  74. package/dist/services/process-runner.js +412 -0
  75. package/dist/services/project-context.js +298 -0
  76. package/dist/services/redaction.js +201 -0
  77. package/dist/services/result-reconciliation.js +49 -0
  78. package/dist/services/secure-store.js +217 -0
  79. package/dist/services/session-resolver.js +113 -0
  80. package/dist/services/sia.js +51 -0
  81. package/dist/services/supported-runtime.js +59 -0
  82. package/dist/services/task-context.js +212 -0
  83. package/dist/services/task-snapshot.js +38 -0
  84. package/dist/services/tool-result-outbox.js +195 -0
  85. package/dist/services/update.js +311 -0
  86. package/dist/services/workspace-registry.js +310 -0
  87. package/dist/services/workspace.js +580 -0
  88. package/dist/shell/shell-chat.js +1297 -59
  89. package/dist/shell/shell-commands.js +243 -12
  90. package/dist/shell/shell-prompt.js +94 -11
  91. package/dist/shell/shell-renderer.js +8 -20
  92. package/dist/shell/shell-router.js +19 -3
  93. package/dist/shell/shell.js +252 -22
  94. package/dist/shell/task-context-view.js +40 -0
  95. package/dist/types/index.js +3 -1
  96. package/dist/ui/agent-cards.js +111 -0
  97. package/dist/ui/agent-presentation.js +131 -0
  98. package/dist/ui/approval.js +111 -0
  99. package/dist/ui/banner.js +31 -48
  100. package/dist/ui/btw-overlay.js +230 -0
  101. package/dist/ui/change-review.js +334 -0
  102. package/dist/ui/chat-renderer.js +207 -14
  103. package/dist/ui/colors.js +12 -8
  104. package/dist/ui/command-details.js +11 -0
  105. package/dist/ui/command-filter.js +26 -5
  106. package/dist/ui/command-palette.js +44 -14
  107. package/dist/ui/command-registry.js +92 -10
  108. package/dist/ui/command-review.js +187 -0
  109. package/dist/ui/composer-layout.js +48 -1
  110. package/dist/ui/conversation.js +450 -0
  111. package/dist/ui/interrupt.js +35 -0
  112. package/dist/ui/live.js +4 -2
  113. package/dist/ui/markdown.js +63 -9
  114. package/dist/ui/message.js +14 -31
  115. package/dist/ui/screen-prompt.js +181 -0
  116. package/dist/ui/screen.js +19 -11
  117. package/dist/ui/select.js +191 -29
  118. package/dist/ui/sia-qa.js +213 -0
  119. package/dist/ui/task-context-card.js +99 -0
  120. package/dist/ui/text-prompt.js +74 -0
  121. package/dist/ui/trust.js +88 -0
  122. package/dist/ui/ui.js +27 -1
  123. package/package.json +18 -4
  124. package/dist/ui/activity.js +0 -77
@@ -0,0 +1,146 @@
1
+ import { heading, kv, line } from "../services/output.js";
2
+ import { discoverRootWithoutGit, branchLabel, refreshWorkspace, shortenRemoteUrl, statusLabel, subPath } from "../services/workspace.js";
3
+ import { c } from "../ui/colors.js";
4
+ import { errorLine } from "../services/output.js";
5
+ import { invalidateProjectContext } from "../services/project-context.js";
6
+ import { activeRepository, getRegistry, listRepositories, repositoryDetails, setActiveRepository } from "../services/workspace-registry.js";
7
+ import { ensureWorkspaceTrust } from "../ui/trust.js";
8
+ /**
9
+ * `cos repo` — what Carrier OS thinks it is looking at.
10
+ *
11
+ * Read-only in the strict sense: it runs `git rev-parse`, `symbolic-ref`,
12
+ * `remote` and `status`, and nothing that writes. There is deliberately no
13
+ * command here to switch branches, stage, or commit — the CLI reports on the
14
+ * repository, it does not drive it.
15
+ *
16
+ * Refreshes rather than reading the cache, because the reason someone types
17
+ * this is usually that they just changed something.
18
+ */
19
+ export function registerRepo(program, ctx) {
20
+ program
21
+ .command("repo")
22
+ .argument("[use]", 'the word "use" to switch repository')
23
+ .argument("[repository]", "repository name from this workspace")
24
+ .description("Show the active repository, or switch with: repo use <name>")
25
+ .action(async (verb, name) => {
26
+ if ((verb ?? "").toLowerCase() === "use") {
27
+ await useRepository(ctx, name);
28
+ return;
29
+ }
30
+ if (verb) {
31
+ errorLine(`Unknown argument "${verb}". Use /repo, or /repo use <repository>.`);
32
+ return;
33
+ }
34
+ // Git runs inside the folder, so the folder is trusted first — decided
35
+ // without starting Git (see discoverRootWithoutGit).
36
+ if (!(await ensureWorkspaceTrust(ctx.config, discoverRootWithoutGit())))
37
+ return;
38
+ render();
39
+ });
40
+ }
41
+ /**
42
+ * Switch the active repository.
43
+ *
44
+ * Selection goes through the registry by NAME — a path is never accepted, so
45
+ * this cannot be used to point the CLI at an arbitrary folder. The new
46
+ * repository carries its own trust: switching into one that was never trusted
47
+ * asks, exactly as opening it would have.
48
+ */
49
+ export async function useRepository(ctx, name) {
50
+ if (!name) {
51
+ errorLine("Which repository? Try /repos to see the list, then /repo use <name>.");
52
+ return;
53
+ }
54
+ let handle;
55
+ try {
56
+ handle = setActiveRepository(name);
57
+ }
58
+ catch (err) {
59
+ errorLine(err.message);
60
+ return;
61
+ }
62
+ if (!(await ensureWorkspaceTrust(ctx.config, handle.root))) {
63
+ line(" " + c.warn("!") + " " + c.dim(`${handle.name} is not trusted — local tools stay off for it.`));
64
+ }
65
+ // The brief and the descriptor both describe "the repository", and that is
66
+ // now a different one.
67
+ invalidateProjectContext();
68
+ refreshWorkspace();
69
+ const details = repositoryDetails(handle, true);
70
+ line();
71
+ line(" " + c.ok("✓") + " " + c.dim("Active repository: ") + c.value(handle.name));
72
+ line(" " + c.dim(handle.root));
73
+ if (details.branch)
74
+ line(" " + c.dim(`branch ${details.branch}`));
75
+ line();
76
+ }
77
+ export function render() {
78
+ // The one caller that displays a remote, so the one that pays for it.
79
+ const ws = refreshWorkspace({ includeRemote: true });
80
+ const repo = ws.repository;
81
+ const registry = getRegistry();
82
+ const active = activeRepository();
83
+ if (registry.workspaceRoot) {
84
+ heading("Workspace");
85
+ kv("Root", registry.workspaceRoot);
86
+ kv("Repositories", listRepositories().map((r) => r.name).join(", "));
87
+ kv("Active", active.name);
88
+ }
89
+ if (repo.state === "detected") {
90
+ heading("Repository");
91
+ kv("Root", repo.root ?? "—");
92
+ const where = subPath(ws);
93
+ // Only worth a line when they are NOT at the root, which is exactly when
94
+ // "Root" alone would be misleading about where commands will act.
95
+ if (where)
96
+ kv("You are in", where);
97
+ kv("Branch", branchLabel(repo) ?? "Unknown");
98
+ if (repo.remote) {
99
+ kv("Remote", repo.remoteUrl ? `${repo.remote} · ${shortenRemoteUrl(repo.remoteUrl)}` : repo.remote);
100
+ }
101
+ else {
102
+ kv("Remote", "Not configured");
103
+ }
104
+ // null means the status could not be taken in budget — usually a very large
105
+ // repository. Saying "Clean" there would be a guess.
106
+ kv("Status", statusLabel(repo) ?? "Unavailable");
107
+ kv("Project", ws.project.name);
108
+ kv("Type", ws.project.label);
109
+ line();
110
+ return;
111
+ }
112
+ // A multi-repository workspace: the launch folder is not itself a repository,
113
+ // so describe the ACTIVE repository rather than the folder holding them.
114
+ if (registry.mode === "workspace") {
115
+ const details = repositoryDetails(active, true);
116
+ heading("Active repository");
117
+ kv("Root", active.root);
118
+ kv("Branch", details.branch ?? "Unknown");
119
+ kv("Status", details.status
120
+ ? details.status.dirty
121
+ ? `${details.status.modified} modified · ${details.status.untracked} untracked`
122
+ : "Clean"
123
+ : "Unavailable");
124
+ kv("Type", details.projectLabel);
125
+ kv("Trust", details.trust === "trusted" ? "Trusted" : "Not trusted");
126
+ line();
127
+ return;
128
+ }
129
+ heading("Workspace");
130
+ kv("Directory", ws.cwd);
131
+ kv("Project", ws.project.name);
132
+ kv("Type", ws.project.label);
133
+ if (repo.state === "unavailable") {
134
+ kv("Git", "Repository information unavailable");
135
+ if (repo.error)
136
+ line(" " + c.dim(repo.error));
137
+ }
138
+ else if (!repo.gitAvailable) {
139
+ kv("Git", "Not detected");
140
+ line(" " + c.dim("Git was not found on your PATH."));
141
+ }
142
+ else {
143
+ kv("Git", "Not detected");
144
+ }
145
+ line();
146
+ }
@@ -0,0 +1,61 @@
1
+ import { line } from "../services/output.js";
2
+ import { activeRepository, inWorkspaceMode, listRepositories, repositoryDetails, getRegistry } from "../services/workspace-registry.js";
3
+ import { c } from "../ui/colors.js";
4
+ import { sectionHeader } from "../ui/ui.js";
5
+ /**
6
+ * `cos repos` — the repositories this workspace knows about.
7
+ *
8
+ * Listing is not access: a repository appears here because it exists next to
9
+ * the others, and each one keeps its own trust state and its own boundary. The
10
+ * marker says which one commands and tools act on right now.
11
+ */
12
+ export function registerRepos(program, _ctx) {
13
+ program
14
+ .command("repos")
15
+ .description("List the repositories in this workspace")
16
+ .action(() => {
17
+ showRepositories();
18
+ });
19
+ }
20
+ function statusText(handle) {
21
+ const d = repositoryDetails(handle);
22
+ const parts = [];
23
+ if (d.status) {
24
+ parts.push(d.status.dirty
25
+ ? [d.status.modified ? `${d.status.modified} modified` : "", d.status.untracked ? `${d.status.untracked} untracked` : ""]
26
+ .filter(Boolean)
27
+ .join(" · ")
28
+ : "clean");
29
+ }
30
+ else if (handle.git) {
31
+ parts.push("status unavailable");
32
+ }
33
+ else {
34
+ parts.push("not a Git repository");
35
+ }
36
+ if (d.trust !== "trusted")
37
+ parts.push("not trusted");
38
+ return parts.join(" · ");
39
+ }
40
+ export function showRepositories() {
41
+ const reg = getRegistry();
42
+ const active = activeRepository();
43
+ line(sectionHeader(inWorkspaceMode() ? "Workspace" : "Repository"));
44
+ if (reg.workspaceRoot)
45
+ line(" " + c.dim(reg.workspaceRoot));
46
+ line();
47
+ for (const handle of listRepositories()) {
48
+ const isActive = handle.id === active.id;
49
+ const marker = isActive ? c.brand("*") : " ";
50
+ const name = isActive ? c.title(handle.name) : c.value(handle.name);
51
+ line(` ${marker} ${name}`);
52
+ const d = repositoryDetails(handle);
53
+ line(" " + c.dim(`branch ${d.branch ?? "unknown"} · ${statusText(handle)}`));
54
+ line(" " + c.dim(handle.root));
55
+ line();
56
+ }
57
+ if (inWorkspaceMode()) {
58
+ line(" " + c.dim("Switch with ") + c.cmd("/repo use <name>") + c.dim(" — tools and commands follow the active repository."));
59
+ line();
60
+ }
61
+ }
@@ -0,0 +1,92 @@
1
+ import { errorLine } from "../services/output.js";
2
+ import { activeRepository, isWildcardSelector, repositoryTrust, resolveRepository } from "../services/workspace-registry.js";
3
+ import { chatTurn } from "../shell/shell-chat.js";
4
+ import { buildFooter } from "../shell/shell-prompt.js";
5
+ /**
6
+ * `/review` — a read-only code review of one repository's uncommitted changes.
7
+ *
8
+ * This is a normal model turn, deliberately constrained: it is sent with the
9
+ * read tools only (read_file, search_files, git_status, git_diff) and NO
10
+ * mutation or command tools, so a review cannot change files or run commands
11
+ * however the model is prompted. It reuses the existing backend orchestration —
12
+ * there is no second agent loop — and the existing conversation renderer, so
13
+ * git activity and file reads appear as the same compact steps as any turn.
14
+ *
15
+ * "Review and fix" is not one step: this produces findings and stops. Fixing is
16
+ * a separate, explicit request that goes through the ordinary mutation flow
17
+ * (with its diffs and approvals). The two are never combined here.
18
+ */
19
+ export function registerReview(program, ctx) {
20
+ program
21
+ .command("review")
22
+ .argument("[repository]", "repository to review (defaults to the active one)")
23
+ .description("Review the uncommitted changes in a repository (read-only)")
24
+ .action(async (repository) => {
25
+ const client = ctx.requireAuth();
26
+ await runReview(ctx, client, repository);
27
+ });
28
+ }
29
+ /**
30
+ * Resolve the repository, refuse anything that is not exactly one trusted
31
+ * registered repository, and run the review turn. The active repository is
32
+ * never changed — a review of a sibling reads the sibling and leaves you where
33
+ * you were.
34
+ */
35
+ export async function runReview(ctx, client, repository, footer) {
36
+ if (isWildcardSelector(repository)) {
37
+ errorLine('Review is one repository at a time — "*" is not accepted. Name a repository, or omit it for the active one.');
38
+ return;
39
+ }
40
+ let handle;
41
+ try {
42
+ handle = repository ? resolveRepository(repository) : activeRepository();
43
+ }
44
+ catch (err) {
45
+ errorLine(err.message);
46
+ return;
47
+ }
48
+ if (repositoryTrust(handle) !== "trusted") {
49
+ errorLine(`${handle.name} is not a trusted repository, so it cannot be reviewed. Run /repo use ${handle.name} and confirm the trust prompt first.`);
50
+ return;
51
+ }
52
+ const display = repository
53
+ ? `Review the changes in ${handle.name}.`
54
+ : "Review the current changes.";
55
+ await chatTurn(ctx, client, display, {
56
+ footer: footer ?? (process.stdin.isTTY ? buildFooter(ctx) : undefined),
57
+ readOnly: true,
58
+ webSearch: false,
59
+ sendAs: reviewPrompt(handle.name)
60
+ });
61
+ }
62
+ /**
63
+ * The task framing sent to the model. It names the repository, drives the
64
+ * git_status → git_diff → read_file flow, fixes the output shape, and is
65
+ * explicit that this is read-only and one repository only. The read-only
66
+ * guarantee does not rest on this text — the turn declares no write tools — but
67
+ * saying so keeps the model from proposing changes it cannot make.
68
+ */
69
+ function reviewPrompt(repository) {
70
+ return [
71
+ `Review the uncommitted changes in the repository "${repository}". This is a READ-ONLY code review.`,
72
+ "",
73
+ "Do this:",
74
+ `1. Call git_status with repository: "${repository}". If the repository is clean (no staged, unstaged or untracked changes), say so in one line and stop — there is nothing to review.`,
75
+ `2. Otherwise call git_diff with repository: "${repository}" (scope "both" to see staged and unstaged together).`,
76
+ `3. Read only the changed files that need a closer look, and just enough surrounding context to judge a finding — use read_file with repository: "${repository}". Do not read the whole project.`,
77
+ "4. Analyse the changes for concrete problems: correctness bugs, regressions, broken edge cases, security issues, unsafe assumptions, missing error handling or validation, race conditions, resource leaks, incorrect API use, and material test-coverage gaps.",
78
+ "",
79
+ "Rules:",
80
+ "- Report only real issues you can point to in the diff or the files you read. A clean review is a valid result — do not invent findings.",
81
+ "- Do not invent line numbers. Cite a file and, where you can map it precisely, a line or range; if you cannot map it exactly, say which file and describe the location without a fabricated number.",
82
+ "- This is read-only. Do not propose or make any file change, and do not run any command. If asked to fix afterwards, the user will make that request separately.",
83
+ "- Review only this one repository.",
84
+ "",
85
+ "Output format:",
86
+ `Start with a one-line header naming the repository. Then, under a "### Findings" heading, one entry per finding as:`,
87
+ "**<Severity> — `<file>:<line or range>`** then a one-line title, then a short \"Why:\" explanation, then a \"Suggested fix:\" line.",
88
+ "Severity is one of critical, high, medium, low, info. Order findings most severe first.",
89
+ 'End with a "### Summary" section: the count by severity, and the line "No files were modified."',
90
+ 'If there are no findings, replace both sections with "### Review complete" and one line saying no concrete issues were found in the current changes.'
91
+ ].join("\n");
92
+ }
@@ -11,7 +11,7 @@ import { screenActive } from "../ui/screen.js";
11
11
  * scope. `target` may be an id or a name; omit it for an interactive picker.
12
12
  */
13
13
  export function registerScope(program, ctx) {
14
- const workspace = program.command("workspace").description("Manage the active workspace");
14
+ const workspace = program.command("workspace").description("Advanced: manage API workspace scope (not local repositories)");
15
15
  workspace
16
16
  .command("list")
17
17
  .description("List your workspaces")
@@ -22,11 +22,11 @@ export function registerScope(program, ctx) {
22
22
  });
23
23
  workspace
24
24
  .command("use [target]")
25
- .description("Switch the active workspace (and pick a project in it)")
25
+ .description("Switch API workspace and automatically select its default project")
26
26
  .action(async (target) => {
27
27
  await useWorkspace(ctx, target);
28
28
  });
29
- const project = program.command("project").description("Manage the active project");
29
+ const project = program.command("project").description("Advanced: manage API project scope (not local repositories)");
30
30
  project
31
31
  .command("list")
32
32
  .description("List projects in the active workspace")
@@ -51,15 +51,16 @@ async function useWorkspace(ctx, target) {
51
51
  if (!ws)
52
52
  return unresolved("workspace", workspaces, activeWorkspaceId(ctx), (w) => `${w.name} ${dim(w.slug)}`);
53
53
  // A workspace switch needs a project in that workspace — pick its default, or
54
- // prompt when interactive.
54
+ // use the server-provided default ordering without a second prompt.
55
55
  const { projects } = await withSpinner("Loading projects…", () => listCliProjects(apiUrl, provider, ws.id));
56
56
  if (projects.length === 0) {
57
57
  errorLine(`Workspace "${ws.name}" has no projects. Create one in the dashboard first.`);
58
58
  process.exitCode = 1;
59
59
  return;
60
60
  }
61
- const proj = (await resolve(projects, undefined, `Select a project in ${ws.name}:`, (p) => `${p.name} (${p.environment})`)) ??
62
- projects[0];
61
+ // The API lists the default project first. Keep a valid current selection
62
+ // when reselecting the same workspace; otherwise use that server ordering.
63
+ const proj = projects.find((p) => p.id === activeProjectId(ctx)) ?? projects[0];
63
64
  await applyScope(ctx, apiUrl, provider, ws.id, proj.id);
64
65
  }
65
66
  async function useProject(ctx, target) {
@@ -97,6 +98,8 @@ async function resolve(items, target, message, labelFn) {
97
98
  return undefined;
98
99
  if (items.length === 0)
99
100
  return undefined;
101
+ if (items.length === 1)
102
+ return items[0];
100
103
  const id = await select({
101
104
  message,
102
105
  choices: items.map((i) => ({ name: labelFn(i), value: i.id }))
@@ -0,0 +1,92 @@
1
+ import { errorLine, line } from "../services/output.js";
2
+ import { searchFiles } from "../services/local-files.js";
3
+ import { discoverRootWithoutGit, getWorkspace } from "../services/workspace.js";
4
+ import { c } from "../ui/colors.js";
5
+ import { watchForInterrupt } from "../ui/interrupt.js";
6
+ import { ensureWorkspaceTrust } from "../ui/trust.js";
7
+ import { sectionHeader } from "../ui/ui.js";
8
+ /**
9
+ * `cos search <query>` — plain text search across the local project.
10
+ *
11
+ * Local and literal. This is the Grep half of the CLI, not the semantic half:
12
+ * it looks for the characters you typed in the files on your disk, nothing is
13
+ * uploaded, and no embedding is involved. Semantic search over a project stays
14
+ * a backend capability reached through chat.
15
+ */
16
+ export function registerSearch(program, ctx) {
17
+ program
18
+ .command("search")
19
+ .argument("<query...>", "text to look for")
20
+ .option("-g, --glob <pattern>", "only search files matching a glob")
21
+ .option("-c, --case-sensitive", "match case exactly")
22
+ .option("-n, --limit <n>", "maximum matches to show", "50")
23
+ .description("Search the local project for text")
24
+ .action(async (queryParts, options) => {
25
+ await runSearch(ctx, queryParts.join(" "), {
26
+ glob: options.glob,
27
+ caseSensitive: Boolean(options.caseSensitive),
28
+ limit: Number.parseInt(options.limit, 10) || 50
29
+ });
30
+ });
31
+ }
32
+ export async function runSearch(ctx, query, opts = {}) {
33
+ if (!query.trim()) {
34
+ errorLine("Usage: /search <text>");
35
+ return;
36
+ }
37
+ // Reading the project is exactly what the folder-trust gate covers, and the
38
+ // scope that matters is the workspace ROOT — that is what the search walks,
39
+ // not just the directory you happen to be standing in.
40
+ if (!(await ensureWorkspaceTrust(ctx.config, discoverRootWithoutGit())))
41
+ return;
42
+ const ws = getWorkspace();
43
+ const label = ws.project.name;
44
+ // Ctrl+C during a long walk. watchForInterrupt is the existing mechanism and
45
+ // attaches only for the duration, so the composer keeps sole ownership of
46
+ // stdin either side of this.
47
+ const controller = new AbortController();
48
+ const stopWatching = watchForInterrupt(() => controller.abort());
49
+ line();
50
+ line(" " + c.dim(`Searching ${label}…`));
51
+ let result;
52
+ try {
53
+ result = searchFiles({
54
+ query,
55
+ glob: opts.glob,
56
+ caseSensitive: opts.caseSensitive,
57
+ limit: opts.limit ?? 50,
58
+ signal: controller.signal
59
+ });
60
+ }
61
+ finally {
62
+ stopWatching();
63
+ }
64
+ if (result.matches.length === 0) {
65
+ line();
66
+ line(" " + c.dim(result.aborted ? "Search cancelled." : "No matches found."));
67
+ line();
68
+ return;
69
+ }
70
+ const count = result.matches.length;
71
+ line();
72
+ line(sectionHeader(`${count} ${count === 1 ? "match" : "matches"} for "${query}"`));
73
+ const width = Math.max(40, (process.stdout.columns ?? 80) - 8);
74
+ for (const m of result.matches) {
75
+ line(" " + c.value(m.path) + c.dim(":") + c.accent(String(m.line)));
76
+ if (m.text)
77
+ line(" " + c.dim(clip(m.text, width)));
78
+ }
79
+ if (result.aborted) {
80
+ line();
81
+ line(" " + c.dim("Cancelled — showing what was found so far."));
82
+ }
83
+ else if (result.truncated) {
84
+ line();
85
+ line(" " + c.dim(`Stopped at ${count}. Narrow it with `) + c.cmd("--glob") + c.dim("."));
86
+ }
87
+ line();
88
+ }
89
+ /** Keep a matching line to one row. */
90
+ function clip(s, max) {
91
+ return [...s].length <= max ? s : [...s].slice(0, max - 1).join("") + "…";
92
+ }