@habitat-ai/cli 0.5.15 → 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 (65) hide show
  1. package/README.md +100 -4
  2. package/dist/application-Idvdhc9h.js +80 -0
  3. package/dist/application.js +2 -18
  4. package/dist/cli-DxjKzwlV.js +4757 -0
  5. package/dist/cli.js +2 -0
  6. package/dist/command-DkmTpQvc.js +74 -0
  7. package/dist/command.d.ts +36 -35
  8. package/dist/command.js +2 -45
  9. package/dist/generators/cli-command.js +263 -0
  10. package/dist/generators/cli-extension.js +192 -0
  11. package/dist/generators/init.js +20 -20
  12. package/dist/generators/preset.js +8 -7
  13. package/dist/generators/remove-hook.js +7 -4
  14. package/dist/generators/service.js +130 -139
  15. package/dist/habitat.app-CgdXa2f2.js +16617 -0
  16. package/dist/habitat.app.js +2 -0
  17. package/dist/host-BcptPYDL.js +293 -0
  18. package/dist/host.d.ts +57 -0
  19. package/dist/host.js +3 -0
  20. package/dist/index.js +8 -5
  21. package/dist/initialization-BWDg3bks.js +249 -0
  22. package/dist/migrations/0-5-7-repository-foundation.js +42 -38
  23. package/dist/nx-generators-DQDXOkMX.js +44 -0
  24. package/dist/nx-generators.js +2 -51
  25. package/dist/nx-plugin.d.ts +4 -1
  26. package/dist/nx-plugin.js +247 -15
  27. package/dist/oclif-DBwcAyVK.js +11 -0
  28. package/dist/oclif.js +3 -0
  29. package/dist/product-version-Bqc0L8lq.js +18 -0
  30. package/dist/publish-generator-tree-CgFdcykY.js +14 -0
  31. package/dist/repository-preset-DYxxe7p3.js +543 -0
  32. package/dist/verified-writes-Cne-zTxS.js +60 -0
  33. package/generators/cli-command/schema.json +20 -0
  34. package/generators/cli-extension/schema.json +20 -0
  35. package/generators/service/files/AGENTS.md.template +5 -2
  36. package/generators/service/files/habitat.toml.template +1 -1
  37. package/generators.json +10 -0
  38. package/oclif.manifest.json +1094 -27
  39. package/package.json +72 -8
  40. package/dist/application.d.ts +0 -14
  41. package/dist/commands/check.d.ts +0 -15
  42. package/dist/commands/check.js +0 -32
  43. package/dist/commands/hook.d.ts +0 -12
  44. package/dist/commands/hook.js +0 -25
  45. package/dist/commands/resolve.d.ts +0 -9
  46. package/dist/commands/resolve.js +0 -15
  47. package/dist/generators/init.d.ts +0 -3
  48. package/dist/generators/preset.d.ts +0 -4
  49. package/dist/generators/remove-hook.d.ts +0 -3
  50. package/dist/generators/service.d.ts +0 -16
  51. package/dist/index.d.ts +0 -1
  52. package/dist/lib/binding.d.ts +0 -10
  53. package/dist/lib/binding.js +0 -16
  54. package/dist/lib/output.d.ts +0 -9
  55. package/dist/lib/output.js +0 -22
  56. package/dist/migrations/0-5-7-repository-foundation.d.ts +0 -3
  57. package/dist/nx/initialization.d.ts +0 -62
  58. package/dist/nx/initialization.js +0 -265
  59. package/dist/nx/projection.d.ts +0 -29
  60. package/dist/nx/projection.js +0 -308
  61. package/dist/nx/repository-preset.d.ts +0 -22
  62. package/dist/nx/repository-preset.js +0 -596
  63. package/dist/nx-generators.d.ts +0 -42
  64. package/dist/product-version.d.ts +0 -2
  65. package/dist/product-version.js +0 -15
@@ -0,0 +1,2 @@
1
+ import { t as habitatApp } from "./habitat.app-CgdXa2f2.js";
2
+ export { habitatApp };
@@ -0,0 +1,293 @@
1
+ import { t as HabitatCommand } from "./command-DkmTpQvc.js";
2
+ import { readOclifCommandSource } from "@habitat-ai/sdk/plugins/cli/oclif";
3
+ import { join } from "node:path";
4
+ import { Config, Errors, flush, handle, run } from "@oclif/core";
5
+ import { readFile } from "node:fs/promises";
6
+ import { SpanStatusCode, context, trace } from "@opentelemetry/api";
7
+ //#region src/harness/oclif/binding.ts
8
+ function readOclifBinding(config) {
9
+ if (!(config instanceof Config) || !("habitatRuntime" in config.options)) throw new TypeError("Native Oclif dispatch has no selected Habitat admission binding.");
10
+ const value = config.options.habitatRuntime;
11
+ if (typeof value !== "object" || value === null || !("invoke" in value) || typeof value.invoke !== "function") throw new TypeError("Native Oclif dispatch has an invalid Habitat process binding.");
12
+ return value;
13
+ }
14
+ /** Native finally owns completion evidence only; waiting for process stop here would deadlock. */
15
+ const FINALLY_HOOK = async function({ config, error }) {
16
+ readOclifBinding(config).onFinally(error);
17
+ };
18
+ function sameCliRef(left, right) {
19
+ return left.kind === right.kind && left.boundary === right.boundary && left.executionId === right.executionId && left.ownerId === right.ownerId && left.commandId === right.commandId;
20
+ }
21
+ //#endregion
22
+ //#region src/harness/oclif/source-bundle.ts
23
+ const bundleIdentity = Symbol("habitat.oclif-source-bundle");
24
+ /** Cold explicit discovery projects only the derivation owner's selected command inventory. */
25
+ function createOclifSourceBundle(derivation) {
26
+ const entries = derivation.cliCommandSources.map(({ ref, source }) => ({
27
+ ref: Object.freeze({ ...ref }),
28
+ source: readOclifCommandSource(source)
29
+ })).sort((left, right) => left.ref.commandId < right.ref.commandId ? -1 : left.ref.commandId > right.ref.commandId ? 1 : 0);
30
+ const commands = Object.create(null);
31
+ for (const entry of entries) {
32
+ const { ref, source } = entry;
33
+ if (Object.hasOwn(commands, ref.commandId)) throw new TypeError("Selected CLI command IDs collide.");
34
+ class SelectedCommand extends HabitatCommand {
35
+ static id = ref.commandId;
36
+ static args = source.args;
37
+ static flags = source.flags;
38
+ async run() {
39
+ const parsed = await this.parse(this.ctor);
40
+ const binding = readOclifBinding(this.config);
41
+ const value = await binding.invoke(ref, source, {
42
+ args: parsed.args,
43
+ flags: parsed.flags
44
+ });
45
+ if (binding.presentation) await source.present(value, this);
46
+ return value;
47
+ }
48
+ }
49
+ Object.assign(SelectedCommand, source.metadata);
50
+ commands[ref.commandId] = SelectedCommand;
51
+ }
52
+ return Object.freeze({
53
+ [bundleIdentity]: true,
54
+ entries: Object.freeze(entries.map((entry) => Object.freeze(entry))),
55
+ COMMANDS: Object.freeze(commands)
56
+ });
57
+ }
58
+ function readOclifSourceBundle(value) {
59
+ if (typeof value !== "object" || value === null || value[bundleIdentity] !== true) throw new TypeError("Native Oclif mounting requires its cold selected source bundle.");
60
+ return value;
61
+ }
62
+ //#endregion
63
+ //#region src/harness/oclif/harness.ts
64
+ /** A single native Oclif invocation; no application or first-party topic is selected here. */
65
+ function createOclifHost(options) {
66
+ const bundle = readOclifSourceBundle(options.sourceBundle);
67
+ const args = [...options.args ?? process.argv.slice(2)];
68
+ const controller = new AbortController();
69
+ let config;
70
+ let mounted = false;
71
+ let consumed = false;
72
+ let presentation = false;
73
+ let active = false;
74
+ let nativeStopping = false;
75
+ let nativeStop;
76
+ let runSettlement;
77
+ let primary;
78
+ let telemetry;
79
+ let startup;
80
+ let startupPromise;
81
+ let started;
82
+ let selected;
83
+ let managedSignals = false;
84
+ let commandSpan;
85
+ function event(name) {
86
+ telemetry?.event(name);
87
+ commandSpan?.addEvent(name);
88
+ }
89
+ function cancel() {
90
+ if (controller.signal.aborted) return;
91
+ controller.abort();
92
+ if (active) event("oclif.cancel");
93
+ }
94
+ function onSignal() {
95
+ primary ??= { error: new Errors.ExitError(1) };
96
+ cancel();
97
+ started?.stop().catch(() => {});
98
+ }
99
+ function installManagedSignals() {
100
+ if (!presentation || managedSignals) return;
101
+ process.on("SIGINT", onSignal);
102
+ process.on("SIGTERM", onSignal);
103
+ managedSignals = true;
104
+ }
105
+ function stopNative() {
106
+ if (nativeStop !== void 0) return nativeStop;
107
+ nativeStopping = true;
108
+ if (active) cancel();
109
+ nativeStop = Promise.resolve(active ? runSettlement : void 0).then(() => {
110
+ config = void 0;
111
+ });
112
+ return nativeStop;
113
+ }
114
+ const binding = Object.freeze({
115
+ get presentation() {
116
+ return presentation;
117
+ },
118
+ async invoke(ref, source, parsed) {
119
+ if (controller.signal.aborted) throw primary?.error ?? new Errors.ExitError(1);
120
+ if (nativeStopping || startup === void 0) throw new TypeError("Native Oclif command intake is closed.");
121
+ if (!bundle.entries.some((entry) => sameCliRef(entry.ref, ref) && entry.source === source)) throw new TypeError("Native Oclif command is outside its selected cold source bundle.");
122
+ installManagedSignals();
123
+ const start = startup;
124
+ startupPromise ??= Promise.resolve().then(() => {
125
+ if (controller.signal.aborted) throw primary?.error ?? new Errors.ExitError(1);
126
+ if (nativeStopping) throw new TypeError("Native Oclif command intake is closed.");
127
+ return start();
128
+ }).then((process) => {
129
+ started = process;
130
+ telemetry = process.telemetry;
131
+ return process;
132
+ });
133
+ await startupPromise;
134
+ if (controller.signal.aborted) throw primary?.error ?? new Errors.ExitError(1);
135
+ if (config === void 0 || nativeStopping || !mounted) throw new TypeError("Native Oclif host is not mounted.");
136
+ const command = selected?.get(ref.executionId);
137
+ if (command === void 0 || !sameCliRef(ref, command.ref) || command.source !== source) throw new TypeError("Native Oclif command is outside its compiled invocation binding.");
138
+ active = true;
139
+ commandSpan = trace.getTracer("habitat.oclif").startSpan(`oclif ${ref.commandId}`, { attributes: {
140
+ "habitat.command.id": ref.commandId,
141
+ "habitat.execution.id": ref.executionId
142
+ } });
143
+ return context.with(trace.setSpan(context.active(), commandSpan), () => command.invoke(parsed, { signal: controller.signal }));
144
+ },
145
+ onFinally(error) {
146
+ if (error !== void 0) primary ??= { error };
147
+ event("oclif.finally");
148
+ }
149
+ });
150
+ async function loadNativeConfig() {
151
+ const loadOptions = {
152
+ root: options.root,
153
+ habitatRuntime: binding,
154
+ ...presentation ? {} : {
155
+ userPlugins: false,
156
+ devPlugins: false
157
+ }
158
+ };
159
+ if (options.discoveryModule !== void 0) loadOptions.pjson = await discoveryPackage(options.root, options.discoveryModule);
160
+ if (controller.signal.aborted) throw primary?.error ?? new Errors.ExitError(1);
161
+ const loaded = await Config.load(loadOptions);
162
+ if (controller.signal.aborted) throw primary?.error ?? new Errors.ExitError(1);
163
+ const rootPlugin = loaded.plugins.get(loaded.name);
164
+ const inventory = rootPlugin?.commands.map((command) => command.id).sort();
165
+ const expected = Object.keys(bundle.COMMANDS).sort();
166
+ if (inventory === void 0 || inventory.length !== expected.length || inventory.some((id, index) => id !== expected[index])) throw new TypeError("Native Oclif discovery differs from the selected command inventory.");
167
+ for (const command of rootPlugin.commands) if (await command.load() !== bundle.COMMANDS[command.id]) throw new TypeError("Native Oclif discovery loaded a different command source.");
168
+ return loaded;
169
+ }
170
+ const descriptor = Object.freeze({
171
+ id: options.harnessId,
172
+ roles: Object.freeze(["cli"]),
173
+ surfaces: Object.freeze(["cli/commands"]),
174
+ async mount(input) {
175
+ if (mounted || nativeStopping) throw new TypeError("An Oclif host can mount only once.");
176
+ if (controller.signal.aborted) throw primary?.error ?? new Errors.ExitError(1);
177
+ if (config === void 0 || startupPromise === void 0) throw new TypeError("An Oclif host mounts only after native command admission.");
178
+ mounted = true;
179
+ const commands = input.mountReadyPayloads.flatMap((record) => record.payload);
180
+ const compiled = /* @__PURE__ */ new Map();
181
+ for (const command of commands) {
182
+ const source = bundle.entries.find((entry) => sameCliRef(entry.ref, command.ref));
183
+ if (source === void 0 || source.source !== command.source || compiled.has(command.ref.executionId)) throw new TypeError("Native Oclif payload does not match the selected cold source bundle.");
184
+ compiled.set(command.ref.executionId, command);
185
+ }
186
+ if (compiled.size !== bundle.entries.length) throw new TypeError("Native Oclif payload omits selected command sources.");
187
+ selected = compiled;
188
+ function health(kind) {
189
+ return Promise.resolve(Object.freeze({
190
+ launchIdentity: input.launchIdentity,
191
+ harnessId: options.harnessId,
192
+ kind,
193
+ status: kind === "liveness" ? "not-applicable" : config === void 0 || nativeStopping ? "failing" : "passing",
194
+ findings: Object.freeze([])
195
+ }));
196
+ }
197
+ return Object.freeze({
198
+ stop: stopNative,
199
+ readiness: () => health("readiness"),
200
+ liveness: () => health("liveness")
201
+ });
202
+ }
203
+ });
204
+ async function invoke(start, terminal) {
205
+ if (consumed) throw new TypeError("An Oclif host can execute only once.");
206
+ if (typeof start !== "function") throw new TypeError("An Oclif host needs a lazy process startup function.");
207
+ consumed = true;
208
+ startup = start;
209
+ presentation = terminal;
210
+ const previousExitCode = process.exitCode;
211
+ let value;
212
+ try {
213
+ runSettlement = Promise.resolve().then(async () => {
214
+ try {
215
+ config = await loadNativeConfig();
216
+ if (controller.signal.aborted) throw primary?.error ?? new Errors.ExitError(1);
217
+ value = await run(args, config);
218
+ } catch (error) {
219
+ primary ??= { error };
220
+ } finally {
221
+ try {
222
+ await flush();
223
+ event("oclif.flush");
224
+ } catch (error) {
225
+ primary ??= { error };
226
+ }
227
+ if (primary !== void 0) commandSpan?.setStatus({ code: SpanStatusCode.ERROR });
228
+ commandSpan?.end();
229
+ commandSpan = void 0;
230
+ active = false;
231
+ }
232
+ });
233
+ await runSettlement;
234
+ } catch (error) {
235
+ primary ??= { error };
236
+ } finally {
237
+ try {
238
+ if (started === void 0) await stopNative();
239
+ else await started.stop();
240
+ } catch (error) {
241
+ primary ??= { error };
242
+ }
243
+ if (managedSignals) {
244
+ process.removeListener("SIGINT", onSignal);
245
+ process.removeListener("SIGTERM", onSignal);
246
+ managedSignals = false;
247
+ }
248
+ if (!terminal) process.exitCode = previousExitCode;
249
+ }
250
+ if (primary !== void 0) {
251
+ if (terminal) {
252
+ event("oclif.handle");
253
+ await handle(primary.error);
254
+ }
255
+ throw primary.error;
256
+ }
257
+ return value;
258
+ }
259
+ return Object.freeze({
260
+ integration: Object.freeze({
261
+ surface: "cli/commands",
262
+ harness: descriptor
263
+ }),
264
+ execute: (start) => invoke(start, true),
265
+ run: (start) => invoke(start, false)
266
+ });
267
+ }
268
+ async function discoveryPackage(root, target) {
269
+ if (target.length === 0) throw new TypeError("Native Oclif discovery needs a module path.");
270
+ const pjson = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
271
+ const commands = pjson.oclif?.commands;
272
+ const finalizer = pjson.oclif?.hooks?.finally;
273
+ if (typeof commands !== "object" || commands === null || commands.strategy !== "explicit" || commands.identifier !== "COMMANDS" || typeof finalizer !== "object" || finalizer === null || Array.isArray(finalizer) || finalizer.identifier !== "FINALLY_HOOK") throw new TypeError("Native Oclif source materialization requires its explicit discovery and finally exports.");
274
+ return {
275
+ ...pjson,
276
+ oclif: {
277
+ ...pjson.oclif,
278
+ commands: {
279
+ ...commands,
280
+ target
281
+ },
282
+ hooks: {
283
+ ...pjson.oclif.hooks,
284
+ finally: {
285
+ ...finalizer,
286
+ target
287
+ }
288
+ }
289
+ }
290
+ };
291
+ }
292
+ //#endregion
293
+ export { createOclifSourceBundle as n, FINALLY_HOOK as r, createOclifHost as t };
package/dist/host.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ import { NativeIntegration, StartedProcess } from "@habitat-ai/sdk/app";
2
+ import { OclifCommandSource } from "@habitat-ai/sdk/plugins/cli/oclif";
3
+ import { Command, Hook } from "@oclif/core";
4
+ import { ExecutionDescriptorRef, RuntimeDerivationResult } from "@habitat-ai/sdk/runtime/derivation";
5
+ //#region src/harness/oclif/binding.d.ts
6
+ type CliExecutionRef = Extract<ExecutionDescriptorRef, {
7
+ boundary: "plugin.cli-command";
8
+ }>;
9
+ /** Native finally owns completion evidence only; waiting for process stop here would deadlock. */
10
+ declare const FINALLY_HOOK: Hook.Finally;
11
+ //#endregion
12
+ //#region src/harness/oclif/source-bundle.d.ts
13
+ declare const bundleIdentity: unique symbol;
14
+ interface OclifSourceBundle {
15
+ readonly [bundleIdentity]: true;
16
+ readonly entries: readonly {
17
+ readonly ref: CliExecutionRef;
18
+ readonly source: OclifCommandSource;
19
+ }[];
20
+ readonly COMMANDS: Readonly<Record<string, Command.Class>>;
21
+ }
22
+ /** Cold explicit discovery projects only the derivation owner's selected command inventory. */
23
+ declare function createOclifSourceBundle(derivation: RuntimeDerivationResult): OclifSourceBundle;
24
+ //#endregion
25
+ //#region src/harness/oclif/harness.d.ts
26
+ interface OclifHostOptions {
27
+ readonly harnessId: string;
28
+ readonly root: string;
29
+ readonly sourceBundle: OclifSourceBundle;
30
+ readonly args?: readonly string[];
31
+ /** Optional native source materialization; selected command membership is unchanged. */
32
+ readonly discoveryModule?: string;
33
+ }
34
+ interface OclifHost {
35
+ readonly integration: Extract<NativeIntegration, {
36
+ surface: "cli/commands";
37
+ }>;
38
+ /** Native terminal invocation; managed signal cancellation begins after command parsing. */
39
+ execute(startup: () => Promise<StartedProcess>): Promise<unknown>;
40
+ /** The same native invocation for an in-process reader, without terminal side effects. */
41
+ run(startup: () => Promise<StartedProcess>): Promise<unknown>;
42
+ }
43
+ /** A single native Oclif invocation; no application or first-party topic is selected here. */
44
+ declare function createOclifHost(options: OclifHostOptions): OclifHost;
45
+ //#endregion
46
+ //#region src/lib/output.d.ts
47
+ /**
48
+ * Writes one complete Habitat command result as JSON before the command returns.
49
+ *
50
+ * Awaiting the stream callback prevents Bun from ending the process while a
51
+ * large stdout write is still buffered at the Oclif process boundary. EPIPE
52
+ * remains successful because it means the downstream pipe deliberately
53
+ * stopped reading, matching Oclif's stdout behavior.
54
+ */
55
+ declare function writeJsonResult(result: unknown): Promise<void>;
56
+ //#endregion
57
+ export { FINALLY_HOOK, type OclifHost, type OclifHostOptions, type OclifSourceBundle, createOclifHost, createOclifSourceBundle, writeJsonResult };
package/dist/host.js ADDED
@@ -0,0 +1,3 @@
1
+ import { n as createOclifSourceBundle, r as FINALLY_HOOK, t as createOclifHost } from "./host-BcptPYDL.js";
2
+ import { n as writeJsonResult } from "./command-DkmTpQvc.js";
3
+ export { FINALLY_HOOK, createOclifHost, createOclifSourceBundle, writeJsonResult };
package/dist/index.js CHANGED
@@ -1,7 +1,10 @@
1
- import { fileURLToPath } from "node:url";
2
- import { executeHabitat } from "./application.js";
1
+ import { t as executeHabitat } from "./application-Idvdhc9h.js";
2
+ import { t as cliPackageRoot } from "./product-version-Bqc0L8lq.js";
3
+ //#region src/index.ts
3
4
  await executeHabitat({
4
- appRoot: fileURLToPath(new URL("..", import.meta.url)),
5
- development: true,
6
- workspaceRoot: process.cwd(),
5
+ appRoot: cliPackageRoot(),
6
+ development: true,
7
+ workspaceRoot: process.cwd()
7
8
  });
9
+ //#endregion
10
+ export {};
@@ -0,0 +1,249 @@
1
+ import { Type } from "typebox";
2
+ import { Validator } from "typebox/schema";
3
+ import { readJson, readNxJson, updateNxJson, writeJson } from "@nx/devkit";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ //#region src/nx/initialization.ts
6
+ const PACKAGE_PATH = "package.json";
7
+ const CODEX_HOOKS_PATH = ".codex/hooks.json";
8
+ const HabitatHookMarkerSchema = Type.Object({
9
+ identity: Type.String({
10
+ minLength: 1,
11
+ description: "Stable package-owned identity for one Habitat hook contribution."
12
+ }),
13
+ revision: Type.Integer({
14
+ minimum: 0,
15
+ description: "Monotonic payload revision for the named Habitat contribution."
16
+ })
17
+ }, {
18
+ additionalProperties: false,
19
+ description: "Habitat hook ownership marker."
20
+ });
21
+ const HookGroupSchema = Type.Object({
22
+ _habitat: Type.Optional(HabitatHookMarkerSchema),
23
+ hooks: Type.Array(Type.Unknown(), { description: "Ordered command contributions in one Codex hook group." })
24
+ }, {
25
+ additionalProperties: true,
26
+ description: "One consumer-owned Codex hook group."
27
+ });
28
+ const HabitatHookCommandSchema = Type.Object({
29
+ type: Type.Literal("command", { description: "Codex hook handler kind owned by the Habitat initializer." }),
30
+ command: Type.String({
31
+ minLength: 1,
32
+ description: "Installed Habitat command executed by the Codex hook."
33
+ }),
34
+ statusMessage: Type.String({
35
+ minLength: 1,
36
+ description: "Operator-facing status rendered while Habitat checks run."
37
+ }),
38
+ timeout: Type.Integer({
39
+ minimum: 1,
40
+ description: "Maximum seconds allowed for the Habitat hook command."
41
+ })
42
+ }, {
43
+ additionalProperties: false,
44
+ description: "One Habitat-owned Codex hook command."
45
+ });
46
+ Type.Object({
47
+ _habitat: HabitatHookMarkerSchema,
48
+ hooks: Type.Array(HabitatHookCommandSchema, {
49
+ minItems: 1,
50
+ description: "Commands contributed by the installed Habitat package."
51
+ })
52
+ }, {
53
+ additionalProperties: false,
54
+ description: "The named Habitat Codex hook contribution."
55
+ });
56
+ const CodexHooksSchema = Type.Object({ hooks: Type.Optional(Type.Record(Type.String(), Type.Array(HookGroupSchema), { description: "Ordered hook groups keyed by Codex event identity." })) }, {
57
+ additionalProperties: true,
58
+ description: "Consumer-owned Codex hook configuration."
59
+ });
60
+ const ConsumerPackageSchema = Type.Object({
61
+ dependencies: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "Runtime dependencies installed directly in the Nx consumer." })),
62
+ scripts: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "Consumer-owned package lifecycle and command scripts." })),
63
+ devDependencies: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "Development tools installed directly in the Nx consumer." })),
64
+ optionalDependencies: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "Optional runtime dependencies installed in the Nx consumer." })),
65
+ peerDependencies: Type.Optional(Type.Record(Type.String(), Type.String(), { description: "Peer dependency contracts declared by the Nx consumer." })),
66
+ trustedDependencies: Type.Optional(Type.Array(Type.String({ minLength: 1 }), { description: "Package lifecycle scripts explicitly trusted by the Bun consumer." }))
67
+ }, {
68
+ additionalProperties: true,
69
+ description: "Nx consumer package metadata."
70
+ });
71
+ const hooksValidator = new Validator({}, CodexHooksSchema);
72
+ const packageValidator = new Validator({}, ConsumerPackageSchema);
73
+ /**
74
+ * Converges one Nx consumer on Habitat's app-owned Nx, Codex, package, and Git-hook state.
75
+ *
76
+ * Every admission and compatibility decision completes before the first Tree
77
+ * write, so an incompatible consumer remains byte-for-byte unchanged.
78
+ */
79
+ function initializeHabitatConsumer(tree, binding) {
80
+ const nxJson = requireNxJson(tree);
81
+ const hooks = readHooks(tree);
82
+ const packageJson = readPackage(tree);
83
+ const nxPlan = planHabitatNxRegistration(nxJson, binding);
84
+ const hookPlan = planHookInitialization(hooks, binding);
85
+ const packagePlan = planPackageInitialization(packageJson, binding);
86
+ const gitHookPlan = planGitHookInitialization(tree, binding.gitHook);
87
+ if (nxPlan.changed) updateNxJson(tree, nxPlan.value);
88
+ if (hookPlan.changed) writeJson(tree, CODEX_HOOKS_PATH, hookPlan.value);
89
+ if (packagePlan.changed) writeJson(tree, PACKAGE_PATH, packagePlan.value);
90
+ if (gitHookPlan.changed) tree.write(binding.gitHook.path, gitHookPlan.value);
91
+ return { packageChanged: packagePlan.changed };
92
+ }
93
+ /** Removes only Habitat's named hook group while preserving installed Nx integration. */
94
+ function removeHabitatHook(tree, binding) {
95
+ const hookPlan = planHookRemoval(readHooks(tree), binding);
96
+ if (hookPlan.changed) writeJson(tree, CODEX_HOOKS_PATH, hookPlan.value);
97
+ }
98
+ function requireNxJson(tree) {
99
+ const nxJson = readNxJson(tree);
100
+ if (nxJson === null) throw new Error("Habitat initialization requires an Nx workspace with nx.json.");
101
+ return nxJson;
102
+ }
103
+ function readHooks(tree) {
104
+ if (!tree.exists(CODEX_HOOKS_PATH)) return { hooks: {} };
105
+ const input = readJson(tree, CODEX_HOOKS_PATH);
106
+ if (!hooksValidator.Check(input)) throw new Error(`${CODEX_HOOKS_PATH} is not a supported Codex hook document.`);
107
+ return input;
108
+ }
109
+ function readPackage(tree) {
110
+ if (!tree.exists(PACKAGE_PATH)) throw new Error("Habitat initialization requires an Nx workspace package.json.");
111
+ const input = readJson(tree, PACKAGE_PATH);
112
+ if (!packageValidator.Check(input)) throw new Error("package.json is not a supported Nx consumer package document.");
113
+ return input;
114
+ }
115
+ /** Plans the one package-owned Nx plugin registration without mutating a Tree. */
116
+ function planHabitatNxRegistration(nxJson, binding) {
117
+ const plugins = nxJson.plugins ?? [];
118
+ const matches = plugins.filter((plugin) => hasPluginIdentity(plugin, binding.nxPlugin) || binding.predecessorNxPlugins.some((predecessor) => hasPluginIdentity(plugin, typeof predecessor === "string" ? predecessor : predecessor.plugin)));
119
+ if (matches.length > 1) throw new Error("nx.json contains multiple Habitat Nx plugin registrations.");
120
+ const match = matches[0];
121
+ if (match === binding.nxPlugin) return {
122
+ changed: false,
123
+ value: nxJson
124
+ };
125
+ if (match !== void 0 && !binding.predecessorNxPlugins.some((predecessor) => isDeepStrictEqual(predecessor, match))) throw new Error("nx.json contains an incompatible Habitat Nx plugin registration.");
126
+ const nextPlugins = match === void 0 ? [...plugins, binding.nxPlugin] : plugins.map((plugin) => plugin === match ? binding.nxPlugin : plugin);
127
+ return {
128
+ changed: true,
129
+ value: {
130
+ ...nxJson,
131
+ plugins: nextPlugins
132
+ }
133
+ };
134
+ }
135
+ function planHookInitialization(hooks, binding) {
136
+ const location = oneOwnedHookLocation(hooks, binding);
137
+ if (location !== void 0 && isDeepStrictEqual(location.group, binding.hook)) return {
138
+ changed: false,
139
+ value: hooks
140
+ };
141
+ if (location !== void 0 && !binding.predecessorHooks.some((predecessor) => isDeepStrictEqual(predecessor, location.group))) throw new Error(`${CODEX_HOOKS_PATH} contains an incompatible Habitat hook contribution.`);
142
+ const events = hooks.hooks ?? {};
143
+ const stop = events.Stop ?? [];
144
+ const nextStop = location === void 0 ? [...stop, binding.hook] : stop.map((group, index) => index === location.index ? binding.hook : group);
145
+ return {
146
+ changed: true,
147
+ value: {
148
+ ...hooks,
149
+ hooks: {
150
+ ...events,
151
+ Stop: nextStop
152
+ }
153
+ }
154
+ };
155
+ }
156
+ function planHookRemoval(hooks, binding) {
157
+ const location = oneOwnedHookLocation(hooks, binding);
158
+ if (location === void 0) return {
159
+ changed: false,
160
+ value: hooks
161
+ };
162
+ if (!isDeepStrictEqual(location.group, binding.hook) && !binding.predecessorHooks.some((predecessor) => isDeepStrictEqual(predecessor, location.group))) throw new Error(`${CODEX_HOOKS_PATH} contains an incompatible Habitat hook contribution.`);
163
+ const events = hooks.hooks ?? {};
164
+ const stop = events.Stop ?? [];
165
+ return {
166
+ changed: true,
167
+ value: {
168
+ ...hooks,
169
+ hooks: {
170
+ ...events,
171
+ Stop: stop.filter((_group, index) => index !== location.index)
172
+ }
173
+ }
174
+ };
175
+ }
176
+ function planPackageInitialization(packageJson, binding) {
177
+ const { gritPackage, husky } = binding;
178
+ const trusted = packageJson.trustedDependencies ?? [];
179
+ const matches = trusted.filter((dependency) => dependency === gritPackage);
180
+ if (matches.length > 1) throw new Error(`package.json contains duplicate ${gritPackage} trust entries.`);
181
+ const currentHuskyVersion = packageJson.devDependencies?.[husky.package];
182
+ const invalidHuskyPlacement = [
183
+ "dependencies",
184
+ "optionalDependencies",
185
+ "peerDependencies"
186
+ ].find((bucket) => packageJson[bucket]?.[husky.package] !== void 0);
187
+ if (invalidHuskyPlacement !== void 0) throw new Error(`package.json must declare ${husky.package} only in devDependencies; found ${invalidHuskyPlacement}.`);
188
+ if (currentHuskyVersion !== void 0 && currentHuskyVersion !== husky.version) throw new Error(`package.json contains an incompatible ${husky.package} version: ${currentHuskyVersion}.`);
189
+ const currentPrepare = packageJson.scripts?.prepare;
190
+ if (currentPrepare !== void 0 && currentPrepare !== husky.prepare && !husky.predecessorPrepareScripts.includes(currentPrepare)) throw new Error("package.json contains an incompatible prepare script.");
191
+ const trustedChanged = matches.length === 0;
192
+ const huskyChanged = currentHuskyVersion === void 0;
193
+ const prepareChanged = currentPrepare !== husky.prepare;
194
+ const currentCheck = packageJson.scripts?.check;
195
+ if (currentCheck !== void 0 && currentCheck.trim().length === 0) throw new Error("package.json contains an empty check script.");
196
+ if (!trustedChanged && !huskyChanged && !prepareChanged && !(currentCheck === void 0)) return {
197
+ changed: false,
198
+ value: packageJson
199
+ };
200
+ return {
201
+ changed: true,
202
+ value: {
203
+ ...packageJson,
204
+ scripts: {
205
+ ...packageJson.scripts,
206
+ check: currentCheck ?? binding.defaultCheckScript,
207
+ prepare: husky.prepare
208
+ },
209
+ devDependencies: {
210
+ ...packageJson.devDependencies,
211
+ [husky.package]: husky.version
212
+ },
213
+ trustedDependencies: trustedChanged ? [...trusted, gritPackage] : trusted
214
+ }
215
+ };
216
+ }
217
+ function planGitHookInitialization(tree, hook) {
218
+ if (!tree.exists(hook.path)) return {
219
+ changed: true,
220
+ value: hook.contents
221
+ };
222
+ const contents = tree.read(hook.path, "utf8");
223
+ if (contents === null || contents.trim().length === 0) throw new Error(`${hook.path} is empty.`);
224
+ return {
225
+ changed: false,
226
+ value: contents
227
+ };
228
+ }
229
+ function oneOwnedHookLocation(hooks, binding) {
230
+ const identity = binding.hook._habitat.identity;
231
+ const locations = Object.entries(hooks.hooks ?? {}).flatMap(([event, groups]) => groups.flatMap((group, index) => {
232
+ const marked = group._habitat?.identity === identity;
233
+ const predecessor = binding.predecessorHooks.some((candidate) => isDeepStrictEqual(candidate, group));
234
+ return marked || predecessor ? [{
235
+ event,
236
+ group,
237
+ index
238
+ }] : [];
239
+ }));
240
+ if (locations.length > 1) throw new Error(`${CODEX_HOOKS_PATH} contains multiple Habitat hook contributions.`);
241
+ const location = locations[0];
242
+ if (location !== void 0 && location.event !== "Stop") throw new Error(`${CODEX_HOOKS_PATH} contains a Habitat hook contribution outside Stop.`);
243
+ return location;
244
+ }
245
+ function hasPluginIdentity(plugin, identity) {
246
+ return plugin === identity || typeof plugin === "object" && plugin.plugin === identity;
247
+ }
248
+ //#endregion
249
+ export { planHabitatNxRegistration as n, removeHabitatHook as r, initializeHabitatConsumer as t };