geloforge 0.0.0-stage → 0.7.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 (90) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +72 -2
  3. package/THIRD_PARTY_NOTICES.md +33 -0
  4. package/VERSION +1 -0
  5. package/adapters/n8n/staging-audit-error-workflow.json +132 -0
  6. package/core/adopt-project.mjs +458 -0
  7. package/core/audit-learning.mjs +68 -0
  8. package/core/audit-provider.mjs +88 -0
  9. package/core/autonomous-audit.mjs +214 -0
  10. package/core/checkpoint.mjs +448 -0
  11. package/core/codebase-map.mjs +886 -0
  12. package/core/compatibility.json +16 -0
  13. package/core/compatibility.mjs +123 -0
  14. package/core/context-cache.mjs +113 -0
  15. package/core/context-compiler.mjs +1315 -0
  16. package/core/evidence-capture.mjs +347 -0
  17. package/core/git-utils.mjs +167 -0
  18. package/core/handoff.mjs +815 -0
  19. package/core/json-schema-lite.mjs +119 -0
  20. package/core/mcp-init.mjs +251 -0
  21. package/core/mcp-server.mjs +915 -0
  22. package/core/operation-approval.mjs +102 -0
  23. package/core/path-safety.mjs +508 -0
  24. package/core/project-locator.mjs +231 -0
  25. package/core/project-lock.mjs +438 -0
  26. package/core/project-status.mjs +635 -0
  27. package/core/project-validator.mjs +544 -0
  28. package/core/promotion.mjs +90 -0
  29. package/core/runtime-files.mjs +40 -0
  30. package/core/skills-history.mjs +572 -0
  31. package/core/skills-lifecycle.mjs +2225 -0
  32. package/core/skills-lint.mjs +365 -0
  33. package/core/skills.mjs +1449 -0
  34. package/core/staging-audit.mjs +454 -0
  35. package/core/staging-evidence.mjs +127 -0
  36. package/core/task-manager.mjs +1044 -0
  37. package/core/template-utils.mjs +190 -0
  38. package/core/text-utils.mjs +48 -0
  39. package/core/verify-task.mjs +48 -0
  40. package/core/worktrees.mjs +64 -0
  41. package/core/yaml-subset.mjs +572 -0
  42. package/package.json +50 -4
  43. package/policies/approval-boundaries.md +42 -0
  44. package/policies/memory-policy.md +53 -0
  45. package/policies/token-efficiency.md +30 -0
  46. package/schemas/README.md +43 -0
  47. package/schemas/adr.schema.json +64 -0
  48. package/schemas/agent-handoff.schema.json +139 -0
  49. package/schemas/approval-record.schema.json +110 -0
  50. package/schemas/conflict-record.schema.json +60 -0
  51. package/schemas/context-pack-manifest.schema.json +194 -0
  52. package/schemas/evidence-manifest.schema.json +83 -0
  53. package/schemas/incident-record.schema.json +53 -0
  54. package/schemas/project-manifest.schema.json +90 -0
  55. package/schemas/project-state.schema.json +64 -0
  56. package/schemas/recovery-checkpoint.schema.json +49 -0
  57. package/schemas/research-record.schema.json +76 -0
  58. package/schemas/task-contract.schema.json +95 -0
  59. package/scripts/bootstrap-project.mjs +357 -0
  60. package/scripts/geloforge.mjs +2512 -0
  61. package/templates/profiles/README.md +19 -0
  62. package/templates/profiles/ai-system/brain/profile.md +21 -0
  63. package/templates/profiles/ai-system/gitignore.append +5 -0
  64. package/templates/profiles/ai-system/profile.json +6 -0
  65. package/templates/profiles/automation/brain/profile.md +19 -0
  66. package/templates/profiles/automation/gitignore.append +5 -0
  67. package/templates/profiles/automation/profile.json +6 -0
  68. package/templates/profiles/desktop/brain/profile.md +21 -0
  69. package/templates/profiles/desktop/gitignore.append +7 -0
  70. package/templates/profiles/desktop/profile.json +6 -0
  71. package/templates/profiles/mobile/brain/profile.md +20 -0
  72. package/templates/profiles/mobile/gitignore.append +8 -0
  73. package/templates/profiles/mobile/profile.json +6 -0
  74. package/templates/profiles/web/brain/profile.md +21 -0
  75. package/templates/profiles/web/gitignore.append +6 -0
  76. package/templates/profiles/web/profile.json +6 -0
  77. package/templates/project-starter/AGENTS.md +27 -0
  78. package/templates/project-starter/GEMINI.md +16 -0
  79. package/templates/project-starter/README.md +26 -0
  80. package/templates/project-starter/brain/INDEX.md +40 -0
  81. package/templates/project-starter/brain/architecture/overview.md +30 -0
  82. package/templates/project-starter/brain/decisions/.gitkeep +0 -0
  83. package/templates/project-starter/brain/manifest.yaml +36 -0
  84. package/templates/project-starter/brain/requirements/constraints.md +29 -0
  85. package/templates/project-starter/brain/requirements/prd.md +37 -0
  86. package/templates/project-starter/brain/state/current.yaml +19 -0
  87. package/templates/project-starter/gitignore.template +25 -0
  88. package/templates/project-starter/src/.gitkeep +0 -0
  89. package/templates/project-starter/tasks/.gitkeep +0 -0
  90. package/templates/project-starter/tests/.gitkeep +0 -0
@@ -0,0 +1,347 @@
1
+ /**
2
+ * Command-backed Verification Evidence Capture for GeloForge.
3
+ * Executes explicit user-supplied argv commands directly with shell: false,
4
+ * redacts secret material, accurately records pass/fail/timeout/error outcomes
5
+ * without overclaiming test correctness, and writes schema-valid EVID-NNNN manifests.
6
+ */
7
+
8
+ import fs from "node:fs";
9
+ import { readRegularFile } from "./runtime-files.mjs";
10
+ import { createHash } from "node:crypto";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import { spawnSync } from "node:child_process";
14
+ import { fileURLToPath } from "node:url";
15
+ import {
16
+ assertSafeWithinRoot,
17
+ isForbiddenSecretPath,
18
+ deriveSlug,
19
+ hasSecretContent,
20
+ redactSecretContent,
21
+ validateScalarText,
22
+ } from "./path-safety.mjs";
23
+ import { serializeYaml } from "./yaml-subset.mjs";
24
+ import { validateAgainstSchema } from "./json-schema-lite.mjs";
25
+ import { getGitRepoInfo } from "./git-utils.mjs";
26
+ import { loadProjectManifestAndState, scanAndAllocateRecordId } from "./project-locator.mjs";
27
+ import { getTask } from "./task-manager.mjs";
28
+ import { runMultiFileTransaction, withProjectLock } from "./project-lock.mjs";
29
+ import { validateCreatedAt } from "./template-utils.mjs";
30
+
31
+ const __filename = fileURLToPath(import.meta.url);
32
+ const __dirname = path.dirname(__filename);
33
+ const DEFAULT_HARNESS_DIR = path.resolve(__dirname, "..");
34
+
35
+ const ALLOWED_ROLES = new Set([
36
+ "orchestrator",
37
+ "researcher",
38
+ "software-architect",
39
+ "developer",
40
+ "qa-security-reviewer",
41
+ ]);
42
+
43
+ const MAX_EXCERPT_CHARS = 480;
44
+ const MAX_BUFFER_BYTES = 2 * 1024 * 1024;
45
+ const DEFAULT_TIMEOUT_MS = 60000;
46
+ const MAX_TIMEOUT_MS = 600000;
47
+
48
+ function formatOutputExcerpt(stdout, stderr) {
49
+ const combinedRaw = [stdout || "", stderr || ""].filter((s) => s.trim().length > 0).join("\n");
50
+ if (!combinedRaw) {
51
+ return "(no stdout/stderr output)";
52
+ }
53
+ const redacted = redactSecretContent(combinedRaw);
54
+ const compact = redacted.replace(/\r?\n/g, " | ").replace(/\s+/g, " ").trim();
55
+ if (compact.length <= MAX_EXCERPT_CHARS) {
56
+ return compact;
57
+ }
58
+ return `${compact.slice(0, MAX_EXCERPT_CHARS - 3)}...`;
59
+ }
60
+
61
+ /**
62
+ * Executes an explicit command (shell: false) inside projectDir and writes an EVID-NNNN manifest.
63
+ */
64
+ export function captureEvidence(options = {}) {
65
+ const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
66
+ if (typeof options.projectDir !== "string" || options.projectDir.trim().length === 0) {
67
+ throw new Error("Missing required project directory (--project <path>).");
68
+ }
69
+
70
+ const commandArgv = options.commandArgv;
71
+ if (!Array.isArray(commandArgv) || commandArgv.length === 0 || commandArgv.some((a) => typeof a !== "string" || a.length === 0)) {
72
+ throw new Error('Missing command to execute after "--". Example: geloforge evidence capture --task TASK-0001 -- node --test');
73
+ }
74
+
75
+ const taskIdRaw = options.taskId;
76
+ if (typeof taskIdRaw !== "string" || !/^TASK-\d{4}$/i.test(taskIdRaw.trim())) {
77
+ throw new Error(`Invalid or missing --task "${taskIdRaw}". Expected TASK-NNNN.`);
78
+ }
79
+ const taskId = taskIdRaw.trim().toUpperCase();
80
+
81
+ const producedByRole = (options.producedByRole || "developer").trim();
82
+ if (!ALLOWED_ROLES.has(producedByRole)) {
83
+ throw new Error(`Invalid --role "${producedByRole}". Expected one of: ${Array.from(ALLOWED_ROLES).join(", ")}`);
84
+ }
85
+
86
+ let timeoutMs = DEFAULT_TIMEOUT_MS;
87
+ if (options.timeoutMs !== undefined && options.timeoutMs !== null) {
88
+ const num = Number(options.timeoutMs);
89
+ if (!Number.isInteger(num) || num < 50 || num > MAX_TIMEOUT_MS) {
90
+ throw new Error(`Invalid --timeout "${options.timeoutMs}". Must be an integer between 50 and ${MAX_TIMEOUT_MS} ms.`);
91
+ }
92
+ timeoutMs = num;
93
+ }
94
+
95
+ const displayCommand = options.displayCommand === undefined
96
+ ? commandArgv.join(" ")
97
+ : validateScalarText("Evidence command display", options.displayCommand);
98
+ const redactedCommand = redactSecretContent(displayCommand);
99
+ const checkName = validateScalarText("--name", options.name ?? `Command check: ${path.basename(commandArgv[0])}`);
100
+ if (hasSecretContent(checkName)) {
101
+ throw new Error("Refusing credential-like content in --name.");
102
+ }
103
+ const createdAt = validateCreatedAt(options.createdAt);
104
+ const dryRun = Boolean(options.dryRun);
105
+ const slug = deriveSlug(checkName) || "check";
106
+ const prepareTarget = () => {
107
+ const loaded = loadProjectManifestAndState(options.projectDir, harnessDir);
108
+ const { projectDir, projectPaths } = loaded;
109
+ const targetTask = getTask({ projectDir, taskId, harnessDir });
110
+ assertSafeWithinRoot(projectDir, projectPaths.evidence_dir);
111
+ const { id } = scanAndAllocateRecordId({
112
+ projectDir,
113
+ searchDirs: [projectPaths.evidence_dir, projectPaths.proposals_dir],
114
+ prefix: "EVID",
115
+ explicitId: options.id ?? null,
116
+ });
117
+ const title = validateScalarText("--title", options.title ?? `Evidence ${id}: ${checkName}`);
118
+ if (hasSecretContent(title)) throw new Error("Refusing credential-like content in --title.");
119
+ const relPath = `${projectPaths.evidence_dir}/${id}-${slug.slice(0, 42)}.yaml`;
120
+ const filePath = assertSafeWithinRoot(projectDir, relPath);
121
+ if (fs.existsSync(filePath)) throw new Error(`Refusing to overwrite existing evidence file: ${filePath}`);
122
+ return { ...loaded, targetTask, id, title, relPath, filePath };
123
+ };
124
+ const initial = dryRun ? prepareTarget() : withProjectLock(options.projectDir, prepareTarget);
125
+ const { projectDir } = initial;
126
+ const readArtifacts = () => (options.artifactPaths || []).map((relativePath) => {
127
+ if (path.isAbsolute(relativePath) || isForbiddenSecretPath(relativePath) || hasSecretContent(relativePath)) {
128
+ throw new Error("Use a safe, project-relative evidence artifact path.");
129
+ }
130
+ const bytes = readRegularFile(assertSafeWithinRoot(projectDir, relativePath));
131
+ if (!bytes || hasSecretContent(bytes.toString("utf8"))) throw new Error("Evidence artifact is missing or unsafe.");
132
+ return {
133
+ path: relativePath, description: "Verified command input",
134
+ sha256: createHash("sha256").update(bytes).digest("hex"),
135
+ };
136
+ });
137
+ const gitInfo = getGitRepoInfo(projectDir);
138
+ const sourceRevision = !gitInfo.available ? "no-git-repo" : gitInfo.unborn ? "git-unborn-head" : gitInfo.head;
139
+ const environment = {
140
+ os: `${process.platform} (${os.release()})`,
141
+ runtime: `Node.js ${process.version}`,
142
+ };
143
+
144
+ if (dryRun) {
145
+ const { id, title, relPath, filePath } = initial;
146
+ const previewRecord = {
147
+ schema_version: "1.1",
148
+ id,
149
+ title,
150
+ task_id: taskId,
151
+ status: "draft",
152
+ memory_layer: "L3_RESEARCH_EVIDENCE",
153
+ authority_level: "A4",
154
+ produced_by_role: producedByRole,
155
+ verified_by: null,
156
+ created_at: createdAt,
157
+ source_revision: sourceRevision,
158
+ environment,
159
+ checks: [
160
+ {
161
+ name: checkName,
162
+ command: redactedCommand,
163
+ result: "not_tested",
164
+ summary: "DRY RUN — command not executed.",
165
+ },
166
+ ],
167
+ artifacts: [],
168
+ limitations: [
169
+ "Dry run only: command was not executed and no evidence file was written.",
170
+ ],
171
+ };
172
+ return {
173
+ dryRun: true,
174
+ id,
175
+ taskId,
176
+ relPath,
177
+ filePath,
178
+ command: redactedCommand,
179
+ exitCode: null,
180
+ timedOut: false,
181
+ checkResult: "not_tested",
182
+ status: "draft",
183
+ verified: false,
184
+ durationMs: 0,
185
+ linkedToTask: false,
186
+ outputExcerpt: "",
187
+ record: previewRecord,
188
+ yaml: serializeYaml(previewRecord, { headerComment: `Evidence Manifest ${id} (dry-run)` }),
189
+ };
190
+ }
191
+
192
+ const artifacts = readArtifacts();
193
+ const [exe, ...cmdArgs] = commandArgv;
194
+ const startedAt = Date.now();
195
+ const proc = spawnSync(exe, cmdArgs, {
196
+ cwd: projectDir,
197
+ shell: false,
198
+ encoding: "utf8",
199
+ timeout: timeoutMs,
200
+ maxBuffer: MAX_BUFFER_BYTES,
201
+ windowsHide: true,
202
+ });
203
+ const durationMs = Math.max(0, Date.now() - startedAt);
204
+
205
+ const excerpt = formatOutputExcerpt(proc.stdout, proc.stderr);
206
+ const timedOut =
207
+ proc.error?.code === "ETIMEDOUT" ||
208
+ Boolean(proc.error && /ETIMEDOUT/i.test(proc.error.message));
209
+
210
+ let checkResult;
211
+ let summary;
212
+ if (timedOut) {
213
+ checkResult = "blocked";
214
+ summary = `Command timed out after ${timeoutMs}ms (${durationMs}ms elapsed); output excerpt: ${excerpt}`;
215
+ } else if (proc.error) {
216
+ checkResult = "blocked";
217
+ const errText = redactSecretContent(proc.error.message || proc.error.code || "spawn failed");
218
+ summary = `Command execution failed to spawn (${proc.error.code || "ERROR"}): ${errText}`;
219
+ } else if (proc.status === 0 && !proc.signal) {
220
+ checkResult = "passed";
221
+ summary = `Exit code 0 in ${durationMs}ms (command execution succeeded under shell: false; output excerpt: ${excerpt})`;
222
+ } else {
223
+ checkResult = "failed";
224
+ const reason = proc.signal ? `signal ${proc.signal}` : `exit code ${proc.status}`;
225
+ summary = `Command failed with ${reason} in ${durationMs}ms; output excerpt: ${excerpt}`;
226
+ }
227
+
228
+ const isVerified = checkResult === "passed";
229
+ const manifestStatus = isVerified ? "verified" : "draft";
230
+ const verifiedBy = isVerified ? (options.verifiedBy || "local-cli-exit-0") : null;
231
+
232
+ const limitations = isVerified
233
+ ? [
234
+ "Exit code 0 proves command execution succeeded in this local environment; it does not independently prove tool-reported test completeness, untested code paths, or broader development claims.",
235
+ "Executed directly with shell: false; stdout/stderr excerpts are bounded and secret-redacted before saving.",
236
+ ]
237
+ : [
238
+ `Command check outcome is "${checkResult}" (${timedOut ? "timed out" : "non-zero/spawn error"}); evidence recorded as status="draft" (NOT verified) and excluded from HANDOFF verified_evidence.`,
239
+ "No test assertions or feature completeness are verified when command execution fails or blocks.",
240
+ ...(proc.error?.code === "ENOENT"
241
+ ? ["Executable not found with shell: false; pass a direct binary path or *.cmd / node command without shell interpolation."]
242
+ : []),
243
+ ];
244
+
245
+ // Run the command outside the project lock, then allocate and link against current state.
246
+ return withProjectLock(projectDir, () => {
247
+ const { schemasDir, state, stateSchema, stateFilePath, targetTask, id, title, relPath, filePath } = prepareTarget();
248
+ if (artifacts.length && JSON.stringify(artifacts) !== JSON.stringify(readArtifacts())) {
249
+ throw new Error("Evidence artifact changed during verification. Retry with a stable copy.");
250
+ }
251
+ const record = {
252
+ schema_version: "1.1",
253
+ id,
254
+ title,
255
+ task_id: taskId,
256
+ status: manifestStatus,
257
+ memory_layer: "L3_RESEARCH_EVIDENCE",
258
+ authority_level: isVerified ? "A3" : "A6",
259
+ produced_by_role: producedByRole,
260
+ verified_by: verifiedBy,
261
+ created_at: createdAt,
262
+ source_revision: sourceRevision,
263
+ environment,
264
+ checks: [
265
+ {
266
+ name: checkName,
267
+ command: redactedCommand,
268
+ result: checkResult,
269
+ summary: redactSecretContent(summary),
270
+ },
271
+ ],
272
+ artifacts,
273
+ limitations: [...limitations, ...(options.limitations || [])].map((l) => redactSecretContent(l)),
274
+ };
275
+
276
+ const evidSchema = JSON.parse(fs.readFileSync(path.join(schemasDir, "evidence-manifest.schema.json"), "utf8"));
277
+ const schemaCheck = validateAgainstSchema(record, evidSchema);
278
+ if (!schemaCheck.valid) {
279
+ throw new Error(`Captured evidence failed schema validation: ${schemaCheck.errors.join("; ")}`);
280
+ }
281
+
282
+ const yamlText = serializeYaml(record, { headerComment: `Evidence Manifest ${id}` });
283
+ const steps = [{ label: "evidence", filePath, content: yamlText, allowOverwrite: false }];
284
+
285
+ const linkedToTask = options.linkTask !== false && (!options.linkVerifiedOnly || isVerified);
286
+ if (linkedToTask) {
287
+ const refs = Array.isArray(targetTask.record.evidence_refs) ? [...targetTask.record.evidence_refs] : [];
288
+ if (!refs.includes(id)) {
289
+ refs.push(id);
290
+ const updatedTask = {
291
+ ...targetTask.record,
292
+ updated_at: createdAt,
293
+ evidence_refs: refs,
294
+ };
295
+ const taskSchema = JSON.parse(fs.readFileSync(path.join(schemasDir, "task-contract.schema.json"), "utf8"));
296
+ const tValid = validateAgainstSchema(updatedTask, taskSchema);
297
+ if (!tValid.valid) {
298
+ throw new Error(`Failed updating task ${taskId} with evidence ref: ${tValid.errors.join("; ")}`);
299
+ }
300
+ steps.push({
301
+ label: "task",
302
+ filePath: targetTask.filePath,
303
+ content: serializeYaml(updatedTask, { headerComment: `Task Contract ${taskId}` }),
304
+ });
305
+ }
306
+
307
+ if (isVerified) {
308
+ const updatedState = {
309
+ ...state,
310
+ state_revision: (state.state_revision ?? 0) + 1,
311
+ updated_at: createdAt,
312
+ last_verified_evidence: id,
313
+ };
314
+ const stValid = validateAgainstSchema(updatedState, stateSchema);
315
+ if (!stValid.valid) {
316
+ throw new Error(`Failed updating state with verified evidence ${id}: ${stValid.errors.join("; ")}`);
317
+ }
318
+ steps.push({
319
+ label: "state",
320
+ filePath: stateFilePath,
321
+ content: serializeYaml(updatedState, { headerComment: "Current Operational Project State" }),
322
+ });
323
+ }
324
+ }
325
+
326
+ runMultiFileTransaction(steps, { projectDir });
327
+ return {
328
+ dryRun: false,
329
+ id,
330
+ taskId,
331
+ relPath,
332
+ filePath,
333
+ command: redactedCommand,
334
+ exitCode: proc.status ?? null,
335
+ signal: proc.signal ?? null,
336
+ timedOut,
337
+ checkResult,
338
+ status: manifestStatus,
339
+ verified: isVerified,
340
+ durationMs,
341
+ linkedToTask,
342
+ outputExcerpt: excerpt,
343
+ record,
344
+ yaml: yamlText,
345
+ };
346
+ });
347
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Shared, project-scoped Git inspection helpers for GeloForge.
3
+ * Ensures subproject operations never leak sibling files from a parent Git repository,
4
+ * handles unborn HEAD and non-Git directories safely, and strips forbidden secret paths.
5
+ */
6
+
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { execFileSync } from "node:child_process";
10
+ import { isForbiddenSecretPath } from "./path-safety.mjs";
11
+
12
+ function runGit(projectDir, args, maxBuffer = 8 * 1024 * 1024) {
13
+ return execFileSync("git", ["-C", projectDir, ...args], {
14
+ encoding: "utf8",
15
+ windowsHide: true,
16
+ maxBuffer,
17
+ stdio: ["ignore", "pipe", "pipe"],
18
+ });
19
+ }
20
+
21
+ export function getGitRepoInfo(projectDir) {
22
+ const resolvedProj = path.resolve(projectDir);
23
+ try {
24
+ const inside = runGit(resolvedProj, ["rev-parse", "--is-inside-work-tree"]).trim();
25
+ if (inside !== "true") {
26
+ return {
27
+ available: false,
28
+ isRepoRoot: false,
29
+ relPrefix: "",
30
+ branch: null,
31
+ head: null,
32
+ unborn: false,
33
+ };
34
+ }
35
+ } catch {
36
+ return {
37
+ available: false,
38
+ isRepoRoot: false,
39
+ relPrefix: "",
40
+ branch: null,
41
+ head: null,
42
+ unborn: false,
43
+ };
44
+ }
45
+
46
+ let isRepoRoot = false;
47
+ let relPrefix = "";
48
+ try {
49
+ // Ask Git directly for the path within the worktree. Git's own prefix is
50
+ // consistent across Windows drive-letter casing and POSIX path spellings.
51
+ // A nested project inside an outer repository must NOT count as its root.
52
+ relPrefix = runGit(resolvedProj, ["rev-parse", "--show-prefix"]).trim().replace(/\\/g, "/").replace(/\/$/, "");
53
+ isRepoRoot = relPrefix === "";
54
+ } catch {
55
+ // Do not infer a Git root from uncertain metadata; prefer safe fallback.
56
+ isRepoRoot = false;
57
+ relPrefix = "";
58
+ }
59
+
60
+ let branch = null;
61
+ try {
62
+ branch = runGit(resolvedProj, ["symbolic-ref", "--short", "HEAD"]).trim() || null;
63
+ } catch {
64
+ try {
65
+ const abbrev = runGit(resolvedProj, ["rev-parse", "--abbrev-ref", "HEAD"]).trim();
66
+ branch = abbrev && abbrev !== "HEAD" ? abbrev : abbrev || null;
67
+ } catch {
68
+ branch = null;
69
+ }
70
+ }
71
+
72
+ let head = null;
73
+ let unborn = false;
74
+ try {
75
+ head = runGit(resolvedProj, ["rev-parse", "HEAD"]).trim() || null;
76
+ } catch {
77
+ head = null;
78
+ unborn = true;
79
+ }
80
+
81
+ return {
82
+ available: true,
83
+ isRepoRoot,
84
+ relPrefix,
85
+ branch,
86
+ head,
87
+ unborn,
88
+ };
89
+ }
90
+
91
+ export function getGitStatusScoped(projectDir, warnings = null) {
92
+ const info = getGitRepoInfo(projectDir);
93
+ if (!info.available) {
94
+ return {
95
+ ...info,
96
+ dirty: false,
97
+ dirtyCount: 0,
98
+ changedFiles: [],
99
+ };
100
+ }
101
+
102
+ const rawChanged = [];
103
+ let entryCount = 0;
104
+ try {
105
+ const statusOut = runGit(projectDir, ["status", "--porcelain", "-z", "-uall", "--", "."]);
106
+ const tokens = statusOut.split("\0").filter(Boolean);
107
+ const prefixSlash = info.relPrefix ? `${info.relPrefix}/` : "";
108
+
109
+ for (let i = 0; i < tokens.length; i += 1) {
110
+ const entry = tokens[i];
111
+ if (entry.length < 4) continue;
112
+ const xy = entry.slice(0, 2);
113
+ let filePath = entry.slice(3).replace(/\\/g, "/");
114
+ if (xy.includes("R") || xy.includes("C")) {
115
+ i += 1;
116
+ }
117
+ if (!info.isRepoRoot && prefixSlash) {
118
+ if (!filePath.startsWith(prefixSlash)) {
119
+ continue;
120
+ }
121
+ filePath = filePath.slice(prefixSlash.length);
122
+ }
123
+ if (!filePath) continue;
124
+ entryCount += 1;
125
+ if (isForbiddenSecretPath(filePath)) {
126
+ if (Array.isArray(warnings)) {
127
+ warnings.push(`Excluded sensitive changed path from git status: ${filePath}`);
128
+ }
129
+ continue;
130
+ }
131
+ rawChanged.push(filePath);
132
+ }
133
+ } catch (err) {
134
+ if (Array.isArray(warnings)) {
135
+ warnings.push(`Unable to collect scoped git status: ${err.message}`);
136
+ }
137
+ }
138
+
139
+ const changedFiles = Array.from(new Set(rawChanged)).sort((a, b) => a.localeCompare(b));
140
+ return {
141
+ ...info,
142
+ dirty: entryCount > 0,
143
+ dirtyCount: entryCount,
144
+ changedFiles,
145
+ };
146
+ }
147
+
148
+ export function listGitVisibleFiles(projectDir, warnings = null) {
149
+ const info = getGitRepoInfo(projectDir);
150
+ if (!info.available || !info.isRepoRoot) {
151
+ return null;
152
+ }
153
+ try {
154
+ const out = runGit(
155
+ projectDir,
156
+ ["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
157
+ 16 * 1024 * 1024
158
+ );
159
+ const paths = out.split("\0").filter(Boolean);
160
+ return { mode: "git-ls-files", paths };
161
+ } catch (err) {
162
+ if (Array.isArray(warnings) && fs.existsSync(path.join(projectDir, ".git"))) {
163
+ warnings.push(`Git discovery failed (${err.message}); falling back to filesystem walk.`);
164
+ }
165
+ return null;
166
+ }
167
+ }