@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,164 @@
1
+ /**
2
+ * Glob patterns, compiled to regular expressions.
3
+ *
4
+ * Written here rather than pulled in as a dependency for two reasons. The CLI
5
+ * ships to npm, so every runtime dependency is install weight and supply-chain
6
+ * surface for its users. And the second consumer is `.gitignore`, whose rules
7
+ * are glob-shaped but carry their own semantics — anchoring, negation,
8
+ * directory-only matching — that no glob package implements. A matcher shared
9
+ * by both is less code than a dependency plus the translation layer it would
10
+ * still need.
11
+ *
12
+ * Paths handed to the compiled expressions are always relative and POSIX-
13
+ * separated. Callers normalize before matching, so nothing here has to think
14
+ * about backslashes.
15
+ */
16
+ /** Characters with meaning in a regular expression but not in a glob. */
17
+ function escapeLiteral(ch) {
18
+ return /[.+^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
19
+ }
20
+ /**
21
+ * Translate one glob body into regex source.
22
+ *
23
+ * The separator rule is the whole point of a glob and the thing a naive
24
+ * implementation gets wrong: `*` stops at a `/`, `**` crosses them. `**\/` is
25
+ * treated as a unit so that `**\/*.ts` matches `a.ts` at the root as well as
26
+ * `src/a.ts` — without that, the leading `/` would be mandatory and the most
27
+ * common pattern anyone types would quietly miss top-level files.
28
+ */
29
+ function translate(glob) {
30
+ let out = "";
31
+ let i = 0;
32
+ while (i < glob.length) {
33
+ const ch = glob[i];
34
+ if (ch === "*") {
35
+ if (glob[i + 1] === "*") {
36
+ // `**/` — any number of leading directories, including none.
37
+ if (glob[i + 2] === "/") {
38
+ out += "(?:[^/]+/)*";
39
+ i += 3;
40
+ continue;
41
+ }
42
+ out += ".*";
43
+ i += 2;
44
+ continue;
45
+ }
46
+ out += "[^/]*";
47
+ i += 1;
48
+ continue;
49
+ }
50
+ if (ch === "?") {
51
+ out += "[^/]";
52
+ i += 1;
53
+ continue;
54
+ }
55
+ if (ch === "[") {
56
+ const cls = readClass(glob, i);
57
+ if (cls) {
58
+ out += cls.source;
59
+ i = cls.next;
60
+ continue;
61
+ }
62
+ // Unterminated — treat as a literal bracket rather than failing.
63
+ out += "\\[";
64
+ i += 1;
65
+ continue;
66
+ }
67
+ if (ch === "{") {
68
+ const alt = readBraces(glob, i);
69
+ if (alt) {
70
+ out += `(?:${alt.parts.map(translate).join("|")})`;
71
+ i = alt.next;
72
+ continue;
73
+ }
74
+ out += "\\{";
75
+ i += 1;
76
+ continue;
77
+ }
78
+ if (ch === "\\" && i + 1 < glob.length) {
79
+ out += escapeLiteral(glob[i + 1]);
80
+ i += 2;
81
+ continue;
82
+ }
83
+ out += escapeLiteral(ch);
84
+ i += 1;
85
+ }
86
+ return out;
87
+ }
88
+ /** `[abc]`, `[!a-z]`, `[]]` — returns regex source and the index after the class. */
89
+ function readClass(glob, start) {
90
+ let i = start + 1;
91
+ let negated = false;
92
+ if (glob[i] === "!" || glob[i] === "^") {
93
+ negated = true;
94
+ i += 1;
95
+ }
96
+ // A `]` in the first position is a literal, per POSIX.
97
+ let body = "";
98
+ if (glob[i] === "]") {
99
+ body += "\\]";
100
+ i += 1;
101
+ }
102
+ while (i < glob.length && glob[i] !== "]") {
103
+ const ch = glob[i];
104
+ body += ch === "\\" || ch === "^" ? `\\${ch}` : ch;
105
+ i += 1;
106
+ }
107
+ if (glob[i] !== "]")
108
+ return null;
109
+ // A class must never match a separator, or `src/[a-z]*` would cross directories.
110
+ return { source: `(?![/])[${negated ? "^" : ""}${body}]`, next: i + 1 };
111
+ }
112
+ /** `{a,b}` — returns the top-level alternatives and the index after the brace. */
113
+ function readBraces(glob, start) {
114
+ let depth = 0;
115
+ const parts = [];
116
+ let current = "";
117
+ for (let i = start; i < glob.length; i += 1) {
118
+ const ch = glob[i];
119
+ if (ch === "{") {
120
+ depth += 1;
121
+ if (depth === 1)
122
+ continue;
123
+ }
124
+ else if (ch === "}") {
125
+ depth -= 1;
126
+ if (depth === 0) {
127
+ parts.push(current);
128
+ return { parts, next: i + 1 };
129
+ }
130
+ }
131
+ else if (ch === "," && depth === 1) {
132
+ parts.push(current);
133
+ current = "";
134
+ continue;
135
+ }
136
+ current += ch;
137
+ }
138
+ return null;
139
+ }
140
+ /**
141
+ * Windows filesystems are case-insensitive, and so is Git there by default
142
+ * (`core.ignorecase`). Matching case-sensitively would mean `*.TS` files
143
+ * silently escaping a `*.ts` pattern on the platform this CLI targets first.
144
+ */
145
+ const CASE_FLAG = process.platform === "win32" ? "i" : "";
146
+ /** Compile a glob anchored to the whole relative path. */
147
+ export function compileGlob(glob) {
148
+ return new RegExp(`^${translate(glob.replace(/^\.\//, ""))}$`, CASE_FLAG);
149
+ }
150
+ /**
151
+ * Compile a `.gitignore` pattern body.
152
+ *
153
+ * `anchored` reflects Git's rule that a pattern containing a slash anywhere but
154
+ * its end is matched from the directory holding the .gitignore, while a bare
155
+ * name like `*.log` matches at any depth.
156
+ */
157
+ export function compileIgnorePattern(pattern, anchored) {
158
+ const body = translate(pattern);
159
+ return new RegExp(anchored ? `^${body}$` : `^(?:.*/)?${body}$`, CASE_FLAG);
160
+ }
161
+ /** Normalize any path to the relative POSIX form the matchers expect. */
162
+ export function toPosix(p) {
163
+ return p.replace(/\\/g, "/").replace(/^\.\//, "");
164
+ }
@@ -0,0 +1,85 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { isPackaged, PACKAGED_DOWNLOAD_URL } from "./packaged.js";
5
+ export function sha256File(file) {
6
+ return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
7
+ }
8
+ const HEX64 = /^[0-9a-f]{64}$/;
9
+ /**
10
+ * The baked helper hashes, or null when the build carries none or carries
11
+ * something malformed. Null is never "anything goes": in packaged mode it means
12
+ * no helper verifies, so the caller fails closed.
13
+ */
14
+ export function bakedHelperHashes(raw = typeof __HELPER_HASHES__ === "string" ? __HELPER_HASHES__ : undefined) {
15
+ if (typeof raw !== "string" || !raw)
16
+ return null;
17
+ try {
18
+ const parsed = JSON.parse(raw);
19
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
20
+ return null;
21
+ const out = {};
22
+ for (const [name, hash] of Object.entries(parsed)) {
23
+ if (!/^[A-Za-z0-9._-]+\.exe$/.test(name) || typeof hash !== "string" || !HEX64.test(hash))
24
+ return null;
25
+ out[name] = hash;
26
+ }
27
+ return Object.keys(out).length ? out : null;
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ function devCandidateDirs(exeDir, env) {
34
+ const dirs = [];
35
+ if (env.COS_HELPER_DIR)
36
+ dirs.push(env.COS_HELPER_DIR);
37
+ dirs.push(exeDir, path.join(exeDir, "bin"));
38
+ return dirs;
39
+ }
40
+ /**
41
+ * The absolute path to a verified prebuilt `<baseName>.exe`, or null.
42
+ *
43
+ * Packaged: null means the installation is damaged — callers must fail closed.
44
+ * Development: null means "none shipped" — callers may compile from source.
45
+ */
46
+ export function findPrebuiltHelper(baseName, opts = {}) {
47
+ const platform = opts.platform ?? process.platform;
48
+ if (platform !== "win32")
49
+ return null;
50
+ const packaged = opts.packaged ?? isPackaged();
51
+ const exeDir = opts.exeDir ?? path.dirname(process.execPath);
52
+ const file = `${baseName}.exe`;
53
+ if (packaged) {
54
+ const hashes = opts.hashes !== undefined ? opts.hashes : bakedHelperHashes();
55
+ const expected = hashes?.[file];
56
+ if (!expected)
57
+ return null;
58
+ const exe = path.join(exeDir, file);
59
+ try {
60
+ return fs.statSync(exe).isFile() && sha256File(exe) === expected ? exe : null;
61
+ }
62
+ catch {
63
+ return null;
64
+ }
65
+ }
66
+ for (const dir of devCandidateDirs(exeDir, opts.env ?? process.env)) {
67
+ const exe = path.join(dir, file);
68
+ const stamp = `${exe}.sha256`;
69
+ try {
70
+ if (!fs.existsSync(exe) || !fs.existsSync(stamp))
71
+ continue;
72
+ const expected = fs.readFileSync(stamp, "utf8").trim();
73
+ if (expected && sha256File(exe) === expected)
74
+ return exe;
75
+ }
76
+ catch {
77
+ /* unreadable candidate — try the next */
78
+ }
79
+ }
80
+ return null;
81
+ }
82
+ /** The message every fail-closed packaged path shows. */
83
+ export function damagedInstallMessage(file) {
84
+ return `This Carrier OS installation is missing or has a damaged component (${file}). Reinstall Carrier OS from ${PACKAGED_DOWNLOAD_URL}.`;
85
+ }
@@ -0,0 +1,189 @@
1
+ import { compileIgnorePattern, toPosix } from "./glob-match.js";
2
+ /**
3
+ * The vocabulary of what counts as noise in a codebase.
4
+ *
5
+ * Mirrored deliberately from the backend rather than written fresh:
6
+ * `SPA_ZIP_SKIP_DIRS` in api.carrieros.ai `src/routes/spa.js`, and the file
7
+ * filter in `src/services/ragService.js`. Those lists are already tuned against
8
+ * real archives and real embedding cost, and the reason to copy them exactly is
9
+ * that a local repository and an uploaded ZIP of the SAME project must resolve
10
+ * to the same set of files. Two vocabularies would mean the CLI and the web
11
+ * answering questions from different views of one codebase, which is far worse
12
+ * than either view being slightly wrong.
13
+ *
14
+ * NOTHING WALKS A DIRECTORY YET. This module exists so that when local
15
+ * traversal lands, there is already one place holding the policy — and so the
16
+ * policy is not quietly reinvented at that point. Keep it in step with the
17
+ * backend; do not extend it here unilaterally.
18
+ */
19
+ /**
20
+ * Directories whose contents are build output, vendored code, or VCS
21
+ * bookkeeping. Stored without the trailing slash the backend uses, because a
22
+ * traversal matches directory NAMES rather than path prefixes.
23
+ */
24
+ export const IGNORED_DIRECTORIES = [
25
+ "node_modules",
26
+ ".git",
27
+ "dist",
28
+ "build",
29
+ ".next",
30
+ "out",
31
+ "vendor",
32
+ "__pycache__",
33
+ ".venv",
34
+ "venv",
35
+ "target",
36
+ "coverage",
37
+ ".idea",
38
+ ".vscode",
39
+ "bower_components",
40
+ ".cache",
41
+ "__macosx"
42
+ ];
43
+ /** Extensions the backend treats as low-signal — assets and generated maps. */
44
+ export const LOW_SIGNAL_EXTENSIONS = [
45
+ ".scss",
46
+ ".less",
47
+ ".svg",
48
+ ".map",
49
+ ".lock",
50
+ ".png",
51
+ ".jpg",
52
+ ".jpeg",
53
+ ".ico",
54
+ ".woff",
55
+ ".woff2"
56
+ ];
57
+ /** Lockfiles and boilerplate manifests — present in every project, meaningful in none. */
58
+ export const IGNORED_FILENAMES = [
59
+ "package-lock.json",
60
+ "yarn.lock",
61
+ "pnpm-lock.yaml",
62
+ ".gitignore",
63
+ ".dockerignore"
64
+ ];
65
+ /** Directory names are compared case-insensitively — Windows, and `__MACOSX`. */
66
+ const IGNORED_DIR_SET = new Set(IGNORED_DIRECTORIES.map((d) => d.toLowerCase()));
67
+ export function isIgnoredDirectory(name) {
68
+ return IGNORED_DIR_SET.has(name.toLowerCase());
69
+ }
70
+ export function ignorePolicy() {
71
+ return {
72
+ directories: IGNORED_DIRECTORIES,
73
+ extensions: LOW_SIGNAL_EXTENSIONS,
74
+ filenames: IGNORED_FILENAMES,
75
+ isIgnoredDirectory
76
+ };
77
+ }
78
+ /**
79
+ * Parse .gitignore text into rules.
80
+ *
81
+ * Implements the parts of the format that actually decide matches: comments,
82
+ * blank lines, `!` negation, a trailing slash for directory-only, a leading
83
+ * slash or an interior slash for anchoring, and `\` escapes. Trailing
84
+ * whitespace is stripped unless escaped, which is the rule that bites anyone
85
+ * who writes `*.log ` with a stray space.
86
+ */
87
+ export function parseGitignore(text, base) {
88
+ const rules = [];
89
+ for (const raw of text.split(/\r?\n/)) {
90
+ let line = raw.replace(/(?<!\\)\s+$/, "");
91
+ if (!line || line.startsWith("#"))
92
+ continue;
93
+ let negated = false;
94
+ if (line.startsWith("!")) {
95
+ negated = true;
96
+ line = line.slice(1);
97
+ }
98
+ // An escaped leading '#' or '!' is a literal.
99
+ if (line.startsWith("\\#") || line.startsWith("\\!"))
100
+ line = line.slice(1);
101
+ if (!line)
102
+ continue;
103
+ let dirOnly = false;
104
+ if (line.endsWith("/")) {
105
+ dirOnly = true;
106
+ line = line.slice(0, -1);
107
+ if (!line)
108
+ continue;
109
+ }
110
+ // Anchored when the pattern says where it lives: a leading slash, or a
111
+ // slash anywhere inside it. A bare `*.log` floats to any depth.
112
+ const anchored = line.startsWith("/") || line.slice(0, -1).includes("/");
113
+ if (line.startsWith("/"))
114
+ line = line.slice(1);
115
+ if (!line)
116
+ continue;
117
+ rules.push({ negated, dirOnly, re: compileIgnorePattern(line, anchored) });
118
+ }
119
+ return { base, rules };
120
+ }
121
+ /**
122
+ * The ignore decision for one walk, as a stack of rule sets.
123
+ *
124
+ * A stack rather than a single list because .gitignore nests: a file's fate is
125
+ * decided by every .gitignore at or above it, nearest last. The walker pushes a
126
+ * set when it descends into a directory that has one and pops it on the way
127
+ * out, so the cost is one parse per .gitignore actually encountered — and it
128
+ * sees them for free, since the directory listing already names them.
129
+ */
130
+ export class IgnoreMatcher {
131
+ #stack = [];
132
+ /** Add the rules from one .gitignore, scoped to `base` and everything under it. */
133
+ push(text, base) {
134
+ this.#stack.push(parseGitignore(text, toPosix(base)));
135
+ }
136
+ /** How many rule sets are active — the walker's restore point. */
137
+ get depth() {
138
+ return this.#stack.length;
139
+ }
140
+ /**
141
+ * Drop rule sets back to a previous depth, used when leaving a subtree.
142
+ *
143
+ * By recorded depth rather than by path prefix: at the root the base is the
144
+ * empty string, and every base starts with that, so a prefix-based pop would
145
+ * clear the entire stack the first time the walker unwound.
146
+ */
147
+ truncate(depth) {
148
+ if (depth < this.#stack.length)
149
+ this.#stack.length = depth;
150
+ }
151
+ /**
152
+ * Should this path be skipped?
153
+ *
154
+ * `relPath` is POSIX and relative to the walk root. Hard excludes are checked
155
+ * first and cannot be negated by a repository — a project that un-ignores
156
+ * `node_modules` still should not have it walked, because the reason to skip
157
+ * it is cost, not the author's preference.
158
+ */
159
+ shouldIgnore(relPath, opts) {
160
+ const posix = toPosix(relPath);
161
+ const name = posix.slice(posix.lastIndexOf("/") + 1);
162
+ if (opts.isDirectory && isIgnoredDirectory(name))
163
+ return true;
164
+ let ignored = false;
165
+ for (const set of this.#stack) {
166
+ // A rule set only governs its own subtree.
167
+ if (set.base && !(posix === set.base || posix.startsWith(`${set.base}/`)))
168
+ continue;
169
+ const scoped = set.base ? posix.slice(set.base.length + 1) : posix;
170
+ if (!scoped)
171
+ continue;
172
+ for (const rule of set.rules) {
173
+ if (rule.dirOnly && !opts.isDirectory)
174
+ continue;
175
+ if (rule.re.test(scoped))
176
+ ignored = !rule.negated;
177
+ }
178
+ }
179
+ return ignored;
180
+ }
181
+ }
182
+ /** True for files the backend treats as low-signal — assets, maps, lockfiles. */
183
+ export function isLowSignalFile(name) {
184
+ const lower = name.toLowerCase();
185
+ if (IGNORED_FILENAMES.includes(lower))
186
+ return true;
187
+ const dot = lower.lastIndexOf(".");
188
+ return dot >= 0 && LOW_SIGNAL_EXTENSIONS.includes(lower.slice(dot));
189
+ }
@@ -0,0 +1,54 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ /** Repository instruction sources, ordered from general to specific. */
4
+ export const INSTRUCTION_FILE_NAMES = ["AGENTS.md", "CLAUDE.md"];
5
+ /**
6
+ * Resolve instruction files that apply to a set of repository-relative
7
+ * directories. Results are ordered root-to-leaf, with AGENTS.md before
8
+ * CLAUDE.md at each scope, so later, narrower guidance can take precedence.
9
+ *
10
+ * This only discovers paths; callers still read the files through the normal
11
+ * containment-checked file reader. In particular, a symlink outside the
12
+ * selected repository is never treated as project guidance.
13
+ */
14
+ export function instructionPathsForDirectories(repositoryRoot, directories) {
15
+ const root = fs.realpathSync.native(repositoryRoot);
16
+ const scopes = new Set(["."]);
17
+ for (const directory of directories) {
18
+ if (typeof directory !== "string" || !directory.trim() || path.isAbsolute(directory) || /[:\0]/.test(directory)) {
19
+ throw new Error("Instruction scopes must be repository-relative paths.");
20
+ }
21
+ const normalized = path.normalize(directory);
22
+ const parts = normalized.split(path.sep).filter((part) => part && part !== ".");
23
+ if (parts.includes(".."))
24
+ throw new Error("Instruction scopes must stay inside the repository.");
25
+ let current = ".";
26
+ for (const part of parts) {
27
+ current = current === "." ? part : path.join(current, part);
28
+ scopes.add(current);
29
+ }
30
+ }
31
+ const orderedScopes = [...scopes].sort((a, b) => {
32
+ const depth = (value) => value === "." ? 0 : value.split(path.sep).length;
33
+ return depth(a) - depth(b) || a.localeCompare(b);
34
+ });
35
+ const found = [];
36
+ for (const scope of orderedScopes) {
37
+ for (const name of INSTRUCTION_FILE_NAMES) {
38
+ const absolute = path.join(root, scope, name);
39
+ try {
40
+ if (!fs.statSync(absolute).isFile())
41
+ continue;
42
+ const actual = fs.realpathSync.native(absolute);
43
+ const relative = path.relative(root, actual);
44
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
45
+ continue;
46
+ found.push(path.relative(root, absolute).split(path.sep).join("/"));
47
+ }
48
+ catch {
49
+ // Missing, unreadable and broken-link instruction files are ignored.
50
+ }
51
+ }
52
+ }
53
+ return found;
54
+ }