Skip to content

Commit 36b1798

Browse files
authored
fix(agents): close project input guard faults in the target inspector (#379)
Follow-up to #346 for HACK-1332 (target inspector contract, HACK-1144 / WU31). ## What changed `hack project target` (and the `hack.project.target` MCP tool) could still return a detail-less error envelope when a shared project input guard refused. The MCP adapter turned that into `data: null`. This PR maps every input-guard fault to a closed, value-free refusal. 1. **Guard refusals (cherry-picked rework 077825fe).** The inspector maps the shared guards' refusals wherever they are raised, including inside config reads: - native or conflicting inputs become `project_inputs_unsupported` - an unparseable, interrupted or uncheckable legacy adoption state (for example an unsearchable `.hack` or `.hack/.internal`) becomes the new provisional `adoption_state_unsafe` - a `.hack` file becomes `input_unreadable` `LegacyComposeAdoptionSelectionError` now carries its `kind`. 2. **Uncheckable input presence (new).** `inputPresent()` in `src/lib/project-input-selection.ts` treats only `ENOENT` as absence. Any other fault threw a plain `Error`, so a `.dev` file, or a mode-000 `.dev` directory, beside a valid `.hack` still produced `E_UNEXPECTED` with no detail. The guard now throws a typed `ProjectInputAccessError`. It is value-free: no OS message, path or `cause`. It classifies the fault as `permission` (`EACCES`/`EPERM`) or `unreadable`. The inspector maps these to `input_permission_denied` and `input_unreadable`. **Side effect on other commands:** the same fault now reports `E_CONFIG_INVALID` instead of `E_UNEXPECTED`. The message text is unchanged except for a trailing "Values omitted.", which matches the adoption guard's input-access refusal. The contract doc (`docs/reference/ax-target-result-contract.md`) and its proof table are updated. ## Validation - Before the fix, the new paired CLI/MCP fixtures returned the off-contract envelope `{"code":"E_UNEXPECTED","message":"Cannot inspect Hack project inputs. …"}`. After the fix, they return the closed refusal, and the envelope contains neither the fixture path nor the errno. - Each new test failed under a mutation: - always classifying as `unreadable` failed the permission domain test and the paired test - restoring the plain `Error` failed both domain tests - disabling the inspector mapping failed both paired tests - Local checks: `packages/cli` typecheck passed. `packages/cli` check reported 0 errors (pre- existing warnings only). Biome on the changed files passed. `privacy:check` passed. gitleaks over `origin/next..HEAD` found no leaks. `tests/project-target-inspect.test.ts` and `tests/project-input-selection.test.ts` gave 52 pass, 0 fail. - Full suite on the M3 at the exact head `85c8ec23`: 7579 pass, 126 skip, 2 fail, across 7707 tests. The mode-000 cases are skipped when running as root. - Both failures are in `tests/native-authored-project-recovery.test.ts`: "new no-host death uses real read-only quiescence facts…" and "new no-host recovery retains original bindings on last-await". - Both also fail on the untouched `next` base `f2278c79` in the same M3 environment (16 pass, 2 fail). The error is "Native process census expired". The real host process census keeps refusing its sessions phase while concurrent suites change the process table, so the 3 s budget expires. - These failures predate this PR and do not touch project inputs. They are reported separately, not fixed here. ## Not changed (noted) `readProjectsRegistry` still treats an unreadable registry as empty. That is pending a product decision (HACK-1332 item 1) and is intentionally left alone here. Refs HACK-1332, HACK-1144. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
1 parent 6b2bd73 commit 36b1798

6 files changed

Lines changed: 286 additions & 25 deletions

‎docs/reference/ax-target-result-contract.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ fixed text that never repeats caller input, paths or registry values.
147147
| `path_not_found` | `E_PROJECT_NOT_FOUND` | `project` | `fix_selector` |
148148
| `no_project_context` | `E_PROJECT_NOT_FOUND` | `project` | `fix_selector` |
149149
| `project_inputs_unsupported` | `E_CONFIG_INVALID` | `project` | `fix_project` |
150+
| `adoption_state_unsafe` | `E_CONFIG_INVALID` | `project` | `fix_project` |
150151
| `config_parse_failed` | `E_CONFIG_PARSE` | `project` | `fix_project` |
151152
| `compose_parse_failed` | `E_CONFIG_PARSE` | `project` | `fix_project` |
152153
| `detached_checkout` | `E_USAGE` | `instance` | `fix_selector` |
@@ -163,6 +164,16 @@ read permission, or a directory where a config file belongs) is reported as
163164
filesystem error). The OS message is never surfaced, because it contains the
164165
absolute path.
165166

167+
The shared project input guards that every project command runs are mapped
168+
too. Native or conflicting project files are `project_inputs_unsupported`. A
169+
legacy adoption state that is unparseable, interrupted, or cannot be checked
170+
(for example a project directory the caller cannot search) is
171+
`adoption_state_unsafe`. A non-directory where the project directory belongs is
172+
`input_unreadable`. When the guard cannot check whether a project input exists
173+
(for example a `.dev` file, or a `.dev` directory the caller cannot search,
174+
beside a valid `.hack`), the refusal is `input_permission_denied` (`EACCES`,
175+
`EPERM`) or `input_unreadable` (any other fault), like a read fault.
176+
166177
`retry` is advice for the caller. Like suggested actions and application logs,
167178
it carries no execution authority.
168179

@@ -208,6 +219,8 @@ WU21). The inspector itself only produces snapshots.
208219
| Two registrations owning one checkout | `ambiguous_project` | same | paired fixture |
209220
| Malformed Hack config or Compose file, oversized input | `config_parse_failed`, `compose_parse_failed`, `generation_input_too_large` | same | paired fixture |
210221
| Unreadable input (directory in place of a file, no read permission) | `input_unreadable`, `input_permission_denied` | same | paired fixture (permission case skipped as root) |
222+
| Input guard refusals (native/legacy conflict, unsafe adoption state, unsearchable or non-directory project dir) | `project_inputs_unsupported`, `adoption_state_unsafe`, `input_unreadable` | same | paired fixture (unsearchable case skipped as root) |
223+
| Uncheckable input presence (`.dev` file or unsearchable `.dev` beside a valid `.hack`) | `input_unreadable`, `input_permission_denied` | same | paired fixture and domain test (unsearchable case skipped as root) |
211224
| Detached linked worktree, no project, missing path | closed refusals | same | paired fixture |
212225
| Unknown service | `service_not_found` | same | paired fixture |
213226
| Config changed during read | `generation_changed_during_read` | same code path | domain test |

‎src/lib/native-compose-adoption-marker.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ export const LEGACY_ADOPTION_SELECTION_MESSAGES = {
3434
} as const;
3535
/** Private owner markers fence upgraded discovery without parsing authored inputs or contacting an engine. */
3636
export class LegacyComposeAdoptionSelectionError extends HackCliError {
37+
/** Which refusal this is, so readers can classify it without its message. */
38+
readonly kind: keyof typeof LEGACY_ADOPTION_SELECTION_MESSAGES;
39+
3740
constructor(
3841
kind: keyof typeof LEGACY_ADOPTION_SELECTION_MESSAGES = "adoption"
3942
) {
@@ -42,6 +45,7 @@ export class LegacyComposeAdoptionSelectionError extends HackCliError {
4245
message: LEGACY_ADOPTION_SELECTION_MESSAGES[kind],
4346
});
4447
this.name = "LegacyComposeAdoptionSelectionError";
48+
this.kind = kind;
4549
}
4650
}
4751
function refuse(): never {

‎src/lib/project-input-selection.ts‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,27 @@ export class ProjectInputSelectionError extends HackCliError {
5757
}
5858
}
5959

60+
/**
61+
* Stable, value-free refusal when a project input's presence cannot be
62+
* checked (for example a file where `.dev` belongs, or a project directory the
63+
* caller cannot search). Only ENOENT means absence, so the guard refuses
64+
* rather than guessing. `access` classifies the fault without its OS message,
65+
* which carries the absolute path and is therefore never kept.
66+
*/
67+
export class ProjectInputAccessError extends HackCliError {
68+
readonly access: "permission" | "unreadable";
69+
70+
constructor(access: "permission" | "unreadable") {
71+
super({
72+
code: "E_CONFIG_INVALID",
73+
message:
74+
"Cannot inspect Hack project inputs. Check filesystem permissions and paths before retrying. Values omitted.",
75+
});
76+
this.name = "ProjectInputAccessError";
77+
this.access = access;
78+
}
79+
}
80+
6081
/**
6182
* Inspect only the named root, without parsing, following authored-file links,
6283
* searching ancestors, touching registration, or normalizing configuration.
@@ -188,12 +209,12 @@ async function inputPresent(path: string): Promise<boolean> {
188209
await lstat(path);
189210
return true;
190211
} catch (error: unknown) {
191-
if (isRecord(error) && error.code === "ENOENT") {
212+
const code = isRecord(error) ? error.code : undefined;
213+
if (code === "ENOENT") {
192214
return false;
193215
}
194-
throw new Error(
195-
"Cannot inspect Hack project inputs. Check filesystem permissions and paths before retrying.",
196-
{ cause: error }
216+
throw new ProjectInputAccessError(
217+
code === "EACCES" || code === "EPERM" ? "permission" : "unreadable"
197218
);
198219
}
199220
}

‎src/lib/target-inspect.ts‎

Lines changed: 52 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
resolveGitCurrentBranch,
1919
} from "./git-worktree.ts";
2020
import { isRecord } from "./guards.ts";
21+
import { LegacyComposeAdoptionSelectionError } from "./native-compose-adoption-marker.ts";
2122
import {
2223
defaultProjectSlugFromPath,
2324
findProjectContext,
@@ -30,7 +31,10 @@ import {
3031
sanitizeBranchSlug,
3132
sanitizeProjectSlug,
3233
} from "./project.ts";
33-
import { ProjectInputSelectionError } from "./project-input-selection.ts";
34+
import {
35+
ProjectInputAccessError,
36+
ProjectInputSelectionError,
37+
} from "./project-input-selection.ts";
3438
import {
3539
AmbiguousProjectNameError,
3640
normalizeProjectName,
@@ -170,6 +174,13 @@ export const TARGET_REFUSALS = Object.freeze({
170174
message:
171175
"The selected project's inputs are not supported by this inspector (native or conflicting project files).",
172176
},
177+
adoption_state_unsafe: {
178+
code: "E_CONFIG_INVALID",
179+
stage: "project",
180+
retry: "fix_project",
181+
message:
182+
"The project's legacy adoption state is unreadable, interrupted or unsafe. Use explicit adoption recovery.",
183+
},
173184
config_parse_failed: {
174185
code: "E_CONFIG_PARSE",
175186
stage: "project",
@@ -357,8 +368,11 @@ export function targetRefusalEnvelope(opts: {
357368
* A filesystem fault while reading inputs (for example a permission-denied
358369
* Compose file, or a directory where a config file belongs) is mapped to the
359370
* closed `input_permission_denied` / `input_unreadable` refusals, so the OS
360-
* message and its absolute path never reach the caller. Only non-filesystem
361-
* faults (programming errors) still throw.
371+
* message and its absolute path never reach the caller. The shared project
372+
* input guards' own refusals (native or conflicting inputs, an unsafe or
373+
* unreadable legacy adoption state, an input whose presence cannot be checked)
374+
* are mapped too, wherever they are raised.
375+
* Only other faults (programming errors) still throw.
362376
*
363377
* `afterResolve` is a test seam that runs after the target is resolved and
364378
* before the generation is re-read; production callers never pass it.
@@ -382,6 +396,10 @@ export async function inspectTarget(opts: {
382396
: { observedGeneration: error.observedGeneration }),
383397
});
384398
}
399+
const guarded = projectInputGuardReason(error);
400+
if (guarded !== null) {
401+
return targetRefusalEnvelope({ reason: guarded });
402+
}
385403
const fault = filesystemFaultCode(error);
386404
if (fault !== null) {
387405
return targetRefusalEnvelope({
@@ -395,6 +413,32 @@ export async function inspectTarget(opts: {
395413
}
396414
}
397415

416+
/**
417+
* Closed reason for a refusal raised by the shared project input guards. Those
418+
* guards run during discovery and again inside every config read, so they are
419+
* classified here rather than at one call site. Their messages are value-free
420+
* but are not catalogue text, so they are never passed through.
421+
*/
422+
function projectInputGuardReason(error: unknown): TargetRefusalReason | null {
423+
if (error instanceof ProjectInputSelectionError) {
424+
return "project_inputs_unsupported";
425+
}
426+
if (error instanceof ProjectInputAccessError) {
427+
return error.access === "permission"
428+
? "input_permission_denied"
429+
: "input_unreadable";
430+
}
431+
if (error instanceof LegacyComposeAdoptionSelectionError) {
432+
if (error.kind === "permission") {
433+
return "input_permission_denied";
434+
}
435+
return error.kind === "input-access"
436+
? "input_unreadable"
437+
: "adoption_state_unsafe";
438+
}
439+
return null;
440+
}
441+
398442
/** Shape of an errno code such as `EACCES` or `EISDIR`. */
399443
const ERRNO_CODE_PATTERN = /^E[A-Z0-9]+$/;
400444

@@ -652,12 +696,10 @@ async function selectProject(opts: {
652696
if (!(await isDirectory(match.repoRoot))) {
653697
throw new TargetRefusal("registered_root_missing");
654698
}
655-
const context = await guardInputs(() =>
656-
findProjectContextAtRoot({
657-
projectRoot: match.repoRoot,
658-
projectDirName: match.projectDirName,
659-
})
660-
);
699+
const context = await findProjectContextAtRoot({
700+
projectRoot: match.repoRoot,
701+
projectDirName: match.projectDirName,
702+
});
661703
if (!context) {
662704
throw new TargetRefusal("no_project_context");
663705
}
@@ -671,24 +713,13 @@ async function selectProject(opts: {
671713
if (opts.selector.path !== null && !(await isDirectory(startDir))) {
672714
throw new TargetRefusal("path_not_found");
673715
}
674-
const context = await guardInputs(() => findProjectContext(startDir));
716+
const context = await findProjectContext(startDir);
675717
if (!context) {
676718
throw new TargetRefusal("no_project_context");
677719
}
678720
return { context, kind: opts.selector.path === null ? "cwd" : "path" };
679721
}
680722

681-
async function guardInputs<T>(read: () => Promise<T>): Promise<T> {
682-
try {
683-
return await read();
684-
} catch (error: unknown) {
685-
if (error instanceof ProjectInputSelectionError) {
686-
throw new TargetRefusal("project_inputs_unsupported");
687-
}
688-
throw error;
689-
}
690-
}
691-
692723
/**
693724
* Registration that owns this exact checkout root: its primary root, or one of
694725
* its recorded linked worktrees. Name equality never matches, so independent

‎tests/project-input-selection.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
discoverProjectInputs,
2929
inspectProjectInputsAtRoot,
3030
NATIVE_PROJECT_FILENAME,
31+
ProjectInputAccessError,
3132
} from "../src/lib/project-input-selection.ts";
3233

3334
const roots: string[] = [];
@@ -197,6 +198,49 @@ test.each([
197198
);
198199
});
199200

201+
async function inputAccessFault(root: string): Promise<unknown> {
202+
try {
203+
await inspectProjectInputsAtRoot({ projectRoot: root });
204+
} catch (error: unknown) {
205+
return error;
206+
}
207+
throw new Error("unexpected input selection success");
208+
}
209+
210+
test("a .dev file beside valid .hack inputs is a typed, value-free access refusal", async () => {
211+
const root = await fixture();
212+
await file(root, ".hack/docker-compose.yml");
213+
await file(root, ".dev", "not a directory");
214+
const error = await inputAccessFault(root);
215+
expect(error).toBeInstanceOf(ProjectInputAccessError);
216+
expect((error as ProjectInputAccessError).access).toBe("unreadable");
217+
expect((error as ProjectInputAccessError).code).toBe("E_CONFIG_INVALID");
218+
expect((error as Error).cause).toBeUndefined();
219+
expect(String(error)).not.toContain(root);
220+
expect(String(error)).not.toContain("ENOTDIR");
221+
});
222+
223+
// Root can search a mode-000 directory, so this fault cannot be produced.
224+
test.skipIf(process.getuid?.() === 0)(
225+
"an unsearchable .dev beside valid .hack inputs is a typed permission refusal",
226+
async () => {
227+
const root = await fixture();
228+
await file(root, ".hack/docker-compose.yml");
229+
const dev = join(root, ".dev");
230+
await mkdir(dev);
231+
await chmod(dev, 0);
232+
try {
233+
const error = await inputAccessFault(root);
234+
expect(error).toBeInstanceOf(ProjectInputAccessError);
235+
expect((error as ProjectInputAccessError).access).toBe("permission");
236+
expect(String(error)).not.toContain(root);
237+
expect(String(error)).not.toContain("EACCES");
238+
} finally {
239+
await chmod(dev, 0o700);
240+
}
241+
}
242+
);
243+
200244
test("supported legacy discovery keeps primary-before-legacy precedence", async () => {
201245
const outer = await fixture();
202246
await file(outer, ".hack/docker-compose.yml");

0 commit comments

Comments
 (0)