@anhlp/alp-core 0.0.1-beta.6 → 0.0.1-beta.8

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 (135) hide show
  1. package/dist/bridges.d.ts +5 -6
  2. package/dist/bridges.js +3 -4
  3. package/dist/library-edit.d.ts +51 -2
  4. package/dist/library-edit.js +160 -8
  5. package/dist/library.d.ts +14 -1
  6. package/dist/library.js +73 -5
  7. package/dist/models.d.ts +35 -0
  8. package/dist/models.js +17 -1
  9. package/dist/packaged.d.ts +37 -45
  10. package/dist/packaged.js +42 -156
  11. package/dist/packs.d.ts +57 -0
  12. package/dist/packs.js +247 -0
  13. package/dist/permissions.d.ts +3 -2
  14. package/dist/permissions.js +6 -3
  15. package/dist/profiles.js +6 -6
  16. package/dist/providers.d.ts +2 -5
  17. package/dist/providers.js +22 -6
  18. package/dist/skill-validate.d.ts +85 -0
  19. package/dist/skill-validate.js +298 -0
  20. package/dist/template-path.d.ts +2 -2
  21. package/dist/template-path.js +0 -5
  22. package/dist/types.d.ts +2 -0
  23. package/dist/upgrade.d.ts +10 -0
  24. package/dist/upgrade.js +112 -6
  25. package/dist/validation.js +6 -6
  26. package/package.json +18 -2
  27. package/src/bridges.js +9 -10
  28. package/src/library-edit.js +170 -8
  29. package/src/library.js +96 -6
  30. package/src/models.js +24 -0
  31. package/src/packaged.js +74 -191
  32. package/src/packs.js +246 -0
  33. package/src/permissions.d.ts +3 -2
  34. package/src/permissions.js +13 -3
  35. package/src/profiles.js +7 -7
  36. package/src/providers.js +22 -8
  37. package/src/resolver.js +1 -1
  38. package/src/skill-validate.js +287 -0
  39. package/src/template-path.js +1 -6
  40. package/src/types.d.ts +2 -0
  41. package/src/upgrade.js +54 -6
  42. package/src/validation.js +8 -7
  43. package/templates/ALP.md +52 -52
  44. package/templates/agents/lead/AGENT.md +77 -74
  45. package/templates/agents/main/AGENT.md +153 -145
  46. package/templates/agents/oracle/AGENT.md +38 -37
  47. package/templates/agents/peer/AGENT.md +56 -52
  48. package/templates/agents/reviewer/AGENT.md +63 -65
  49. package/templates/agents/supervisor/AGENT.md +63 -63
  50. package/templates/packs/architecture/agents/architect/AGENT.md +41 -0
  51. package/templates/packs/architecture/agents/architect/agent.json +5 -0
  52. package/templates/packs/architecture/agents/docs-maintainer/AGENT.md +33 -0
  53. package/templates/packs/architecture/agents/docs-maintainer/agent.json +4 -0
  54. package/templates/packs/architecture/pack.json +7 -0
  55. package/templates/packs/architecture/teams/blueprint/HOUSE_RULES.md +12 -0
  56. package/templates/packs/architecture/teams/blueprint/team.json +19 -0
  57. package/templates/packs/backend/pack.json +6 -0
  58. package/templates/packs/backend/skills/backend-development/SKILL.md +102 -0
  59. package/templates/packs/backend/skills/backend-development/references/api-design.md +96 -0
  60. package/templates/packs/backend/skills/backend-development/references/authentication.md +78 -0
  61. package/templates/packs/backend/skills/backend-development/references/error-handling.md +86 -0
  62. package/templates/packs/backend/skills/backend-development/references/testing.md +81 -0
  63. package/templates/packs/backend/skills/databases/SKILL.md +103 -0
  64. package/templates/packs/backend/skills/databases/references/query-performance.md +87 -0
  65. package/templates/packs/backend/skills/databases/references/schema-and-migrations.md +87 -0
  66. package/templates/packs/design/pack.json +6 -0
  67. package/templates/packs/design/skills/ui-design/SKILL.md +86 -0
  68. package/templates/packs/design/skills/ui-design/references/design-tokens.md +67 -0
  69. package/templates/packs/design/skills/ui-design/references/interaction-states.md +73 -0
  70. package/templates/packs/design/skills/ui-design/references/layout-and-typography.md +71 -0
  71. package/templates/packs/design/skills/ui-design/references/ui-review.md +83 -0
  72. package/templates/packs/frontend/pack.json +6 -0
  73. package/templates/packs/frontend/skills/frontend-development/SKILL.md +105 -0
  74. package/templates/packs/frontend/skills/frontend-development/references/accessibility.md +86 -0
  75. package/templates/packs/frontend/skills/frontend-development/references/components-and-state.md +79 -0
  76. package/templates/packs/frontend/skills/frontend-development/references/data-fetching.md +86 -0
  77. package/templates/packs/frontend/skills/frontend-development/references/frameworks.md +77 -0
  78. package/templates/packs/frontend/skills/frontend-development/references/performance.md +78 -0
  79. package/templates/packs/integration/pack.json +6 -0
  80. package/templates/packs/integration/skills/mcp-integration/SKILL.md +100 -0
  81. package/templates/packs/integration/skills/mcp-integration/references/server-implementation.md +95 -0
  82. package/templates/packs/integration/skills/mcp-integration/references/testing.md +78 -0
  83. package/templates/packs/integration/skills/mcp-integration/references/tool-design.md +97 -0
  84. package/templates/packs/operations/pack.json +6 -0
  85. package/templates/packs/operations/skills/devops/SKILL.md +85 -0
  86. package/templates/packs/operations/skills/devops/references/ci-cd.md +84 -0
  87. package/templates/packs/operations/skills/devops/references/containers.md +85 -0
  88. package/templates/packs/operations/skills/devops/references/deployment-and-rollback.md +85 -0
  89. package/templates/packs/operations/skills/devops/references/observability.md +86 -0
  90. package/templates/packs/quality/pack.json +6 -0
  91. package/templates/packs/quality/skills/web-testing/SKILL.md +102 -0
  92. package/templates/packs/quality/skills/web-testing/references/e2e.md +85 -0
  93. package/templates/packs/quality/skills/web-testing/references/performance-testing.md +85 -0
  94. package/templates/packs/quality/skills/web-testing/references/security-testing.md +78 -0
  95. package/templates/packs/quality/skills/web-testing/references/unit-and-component.md +78 -0
  96. package/templates/role-skills.json +4 -4
  97. package/templates/skills/architecture-docs/SKILL.md +81 -0
  98. package/templates/skills/architecture-docs/references/adr.md +62 -0
  99. package/templates/skills/architecture-docs/references/diagrams.md +60 -0
  100. package/templates/skills/architecture-docs/references/evidence-rules.md +49 -0
  101. package/templates/skills/bug-loop/SKILL.md +41 -40
  102. package/templates/skills/bug-loop/references/test-proof.md +21 -19
  103. package/templates/skills/compact/SKILL.md +2 -2
  104. package/templates/skills/curate/SKILL.md +6 -5
  105. package/templates/skills/feature-architecture/SKILL.md +90 -0
  106. package/templates/skills/feature-architecture/references/architecture-contract.md +95 -0
  107. package/templates/skills/feature-architecture/references/feature-design.md +69 -0
  108. package/templates/skills/feature-architecture/scripts/check-boundaries.mjs +270 -0
  109. package/templates/skills/goal-griller/SKILL.md +27 -27
  110. package/templates/skills/prompt-leverage/SKILL.md +29 -27
  111. package/templates/skills/prompt-leverage/references/brief-template.md +9 -9
  112. package/templates/skills/release-readiness/SKILL.md +83 -0
  113. package/templates/skills/release-readiness/references/checklist.md +40 -0
  114. package/templates/skills/release-readiness/references/verdict-template.md +53 -0
  115. package/templates/skills/safe-refactor/SKILL.md +84 -0
  116. package/templates/skills/safe-refactor/references/characterization-tests.md +57 -0
  117. package/templates/skills/safe-refactor/references/compatibility-checklist.md +56 -0
  118. package/templates/skills/security-review/SKILL.md +87 -0
  119. package/templates/skills/security-review/references/checklist.md +74 -0
  120. package/templates/skills/security-review/references/severity.md +61 -0
  121. package/templates/skills/sequence-execution-plan/SKILL.md +41 -38
  122. package/templates/skills/sequence-execution-plan/references/plan-template.md +5 -5
  123. package/templates/skills/skill-authoring/SKILL.md +84 -0
  124. package/templates/skills/skill-authoring/references/evaluation.md +45 -0
  125. package/templates/skills/skill-authoring/references/skill-anatomy.md +74 -0
  126. package/templates/skills/skill-authoring/references/trigger-design.md +52 -0
  127. package/templates/skills/smart-commits/SKILL.md +37 -36
  128. package/templates/skills/test-strategy/SKILL.md +83 -0
  129. package/templates/skills/test-strategy/references/contract-tests.md +46 -0
  130. package/templates/skills/test-strategy/references/risk-matrix.md +53 -0
  131. package/templates/skills/xia/SKILL.md +40 -38
  132. package/templates/teams/cafe/HOUSE_RULES.md +1 -1
  133. package/templates/teams/cafe/team.json +1 -1
  134. package/templates/teams/pho/HOUSE_RULES.md +1 -1
  135. package/templates/teams/pho/team.json +1 -1
@@ -1,16 +1,20 @@
1
1
  /**
2
- * @typedef {{ path: string, sha256: string, size: number }} PackagedAsset
3
- * @typedef {{ version: string, assets?: Record<string, PackagedAsset>, roles?: Record<string, () => Promise<unknown>>, modules?: Record<string, () => Promise<unknown>> }} PackagedRegistration
2
+ * The ALP bundle this Node belongs to, or undefined for any other Node (an npm install).
3
+ * @param {string} [execPath]
4
+ * @returns {BundleInfo | undefined}
5
+ */
6
+ export function bundleInfo(execPath?: string): BundleInfo | undefined;
7
+ /**
8
+ * `file` named through `<app>/current` when it lies inside this process's bundle and `current` points
9
+ * at that bundle; otherwise `file` unchanged. For paths written to disk for later processes.
10
+ * @param {string} file
11
+ * @param {{ bundle?: BundleInfo | undefined }} [options]
4
12
  */
5
- /** Called once by the executable's entry. @param {PackagedRegistration} registration */
6
- export function registerPackaged(registration: PackagedRegistration): void;
7
- /** The registration when this process is the ALP executable, else undefined. @returns {PackagedRegistration | undefined} */
8
- export function packagedInfo(): PackagedRegistration | undefined;
9
- /** Whether this process is the self-contained ALP executable. */
10
- export function isPackaged(): boolean;
13
+ export function stablePath(file: string, { bundle }?: {
14
+ bundle?: BundleInfo | undefined;
15
+ }): string;
11
16
  /**
12
- * The command that starts ALP's `role` from this process: the executable's subcommand when packaged,
13
- * else `script` under this Node, exactly as before.
17
+ * The command that starts ALP's `role` from this process: `script` under this Node.
14
18
  * @param {keyof typeof ROLE_ARGS} role
15
19
  * @param {{ script: string, args?: string[] }} options
16
20
  * @returns {{ command: string, args: string[] }}
@@ -24,7 +28,8 @@ export function selfCommand(role: keyof typeof ROLE_ARGS, { script, args }: {
24
28
  };
25
29
  /**
26
30
  * The command that runs an `entry` found on disk (an install record, a service definition, a CLI
27
- * on PATH): a script runs under `execPath`; an executable runs its own role subcommand.
31
+ * on PATH): a script runs under `execPath`; an `alp` command (the bundle's launcher, or what a
32
+ * 0.0.1-beta.5/6 single-file install recorded) runs its role subcommand.
28
33
  * @param {string} entry
29
34
  * @param {keyof typeof ROLE_ARGS} role
30
35
  * @param {string[]} [args]
@@ -39,8 +44,7 @@ export function entryCommand(entry: string, role: keyof typeof ROLE_ARGS, args?:
39
44
  args: string[];
40
45
  };
41
46
  /**
42
- * The command that runs a user's JavaScript file (a fake provider, an npm cmd shim on Windows)
43
- * with this process's runtime. The executable runs it as Bun does when BUN_BE_BUN is set.
47
+ * The command that runs a user's JavaScript file (a fake provider, an npm cmd shim on Windows) with this Node.
44
48
  * @param {string} script
45
49
  * @param {string[]} [args]
46
50
  * @returns {{ command: string, args: string[], env?: Record<string, string> }}
@@ -50,48 +54,36 @@ export function scriptCommand(script: string, args?: string[]): {
50
54
  args: string[];
51
55
  env?: Record<string, string>;
52
56
  };
53
- /** The ALP executable's path when this process is it, else undefined. */
54
- export function executablePath(): string | undefined;
55
- /** Where this process's own entry lives: the executable when packaged, else `script`. @param {string} script */
57
+ /** Where this process's own entry lives, for records that later processes read: `script`, through `current` in a bundle. @param {string} script */
56
58
  export function selfEntry(script: string): string;
57
- /** The directory the executable's assets are extracted to. @param {string} version @param {NodeJS.ProcessEnv} [env] */
58
- export function assetCacheDir(version: string, env?: NodeJS.ProcessEnv): string;
59
59
  /**
60
- * The directory holding the executable's embedded assets (templates, the web app, the native
61
- * terminal helper), extracted once per version to `<ALP_HOME or ~/.alp>/cache/<version>/` and
62
- * checked against the build's sha256 manifest. Undefined when not packaged: callers then use the
63
- * files beside their scripts, as before.
64
- * @param {{ env?: NodeJS.ProcessEnv, info?: PackagedRegistration }} [options]
65
- * @returns {string | undefined}
60
+ * How ALP starts its own processes, and where its bundle lives. ALP always runs under Node: from npm
61
+ * (`node cli.js`, `node alpd.js`) or from the ALP bundle (t-1807), which is the same npm install
62
+ * beside an official Node release, started by `bin/alp`:
63
+ *
64
+ * <app>/<version>/{bin/alp, node/bin/node, lib/node_modules/@anhlp/alp-cli, alp-bundle.json}
65
+ * <app>/current → <version> (install.sh and `alp update` move it)
66
+ *
67
+ * Paths that outlive this process (a launchd/systemd service, alpd's install record) name the bundle
68
+ * through `current`, so an update never leaves them on a removed version.
66
69
  */
67
- export function assetDir({ env, info }?: {
68
- env?: NodeJS.ProcessEnv;
69
- info?: PackagedRegistration;
70
- }): string | undefined;
71
- /** Subcommands of the executable that run each ALP role (the npm CLI understands them too). */
70
+ /** Subcommands of `alp` that run each ALP role in that process (`alp daemon run`, `alp web serve`, `alp bridge acp`). */
72
71
  export const ROLE_ARGS: Readonly<{
73
72
  daemon: readonly string[];
74
73
  web: readonly string[];
75
74
  'bridge-acp': readonly string[];
76
75
  'bridge-antigravity': readonly string[];
77
76
  }>;
78
- /**
79
- * A string only ALP's executable carries: its generated entry embeds it, so discovery can tell ALP
80
- * from an unrelated native program that happens to be called `alp` without running it.
81
- */
82
- export const EXECUTABLE_MARKER: "alp-standalone-executable:v1:2b6f0c1e";
83
77
  export function isExecutableName(file: string): boolean;
84
- export function isSelf(file: unknown): boolean;
85
- export function samePath(a: string, b: string): boolean;
86
78
  export function isScript(file: string): boolean;
87
- export type PackagedAsset = {
88
- path: string;
89
- sha256: string;
90
- size: number;
91
- };
92
- export type PackagedRegistration = {
79
+ export function samePath(a: string, b: string): boolean;
80
+ /**
81
+ * root: the bundle directory (real path); app: its parent; current: `<app>/current` when it points at root.
82
+ */
83
+ export type BundleInfo = {
84
+ root: string;
93
85
  version: string;
94
- assets?: Record<string, PackagedAsset>;
95
- roles?: Record<string, () => Promise<unknown>>;
96
- modules?: Record<string, () => Promise<unknown>>;
86
+ platform: string;
87
+ app: string;
88
+ current?: string;
97
89
  };
package/dist/packaged.js CHANGED
@@ -1,31 +1,14 @@
1
1
  // packages/core/src/packaged.js
2
- import { createHash } from "node:crypto";
3
- import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
- import os from "node:os";
2
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
5
3
  import path from "node:path";
6
- var KEY = Symbol.for("alp.packaged");
7
4
  var ROLE_ARGS = Object.freeze({
8
5
  daemon: Object.freeze(["daemon", "run"]),
9
6
  web: Object.freeze(["web", "serve"]),
10
7
  "bridge-acp": Object.freeze(["bridge", "acp"]),
11
8
  "bridge-antigravity": Object.freeze(["bridge", "antigravity"])
12
9
  });
13
- function registerPackaged(registration) {
14
- if (!registration || typeof registration.version !== "string") throw new TypeError("registerPackaged needs a version");
15
- Object.defineProperty(globalThis, KEY, { value: Object.freeze({ ...registration, assetDir: () => assetDir() }), configurable: true, enumerable: false, writable: false });
16
- }
17
- function packagedInfo() {
18
- return (
19
- /** @type {any} */
20
- globalThis[KEY]
21
- );
22
- }
23
- function isPackaged() {
24
- return packagedInfo() !== void 0;
25
- }
26
- var EXECUTABLE_MARKER = "alp-standalone-executable:v1:2b6f0c1e";
27
- var isExecutableName = (file) => /^alp(\.exe)?$/i.test(file.split(/[\\/]/).pop() ?? "");
28
- var isSelf = (file) => isPackaged() && typeof file === "string" && samePath(file, process.execPath);
10
+ var isExecutableName = (file) => /^alp(\.exe|\.cmd)?$/i.test(file.split(/[\\/]/).pop() ?? "");
11
+ var isScript = (file) => /\.[cm]?js$/i.test(file);
29
12
  var canonical = (file) => {
30
13
  let resolved = path.resolve(file);
31
14
  try {
@@ -35,164 +18,67 @@ var canonical = (file) => {
35
18
  return process.platform === "darwin" || process.platform === "win32" ? resolved.toLowerCase() : resolved;
36
19
  };
37
20
  var samePath = (a, b) => canonical(a) === canonical(b);
38
- var isScript = (file) => /\.[cm]?js$/i.test(file);
39
21
  function roleArgs(role) {
40
22
  const args = ROLE_ARGS[role];
41
23
  if (!args) throw new TypeError(`Unknown ALP role: ${role}`);
42
24
  return [...args];
43
25
  }
26
+ var bundles = /* @__PURE__ */ new Map();
27
+ function bundleInfo(execPath = process.execPath) {
28
+ if (bundles.has(execPath)) return bundles.get(execPath);
29
+ let info;
30
+ try {
31
+ const real = realpathSync(execPath);
32
+ const nodeDir = path.basename(path.dirname(real)) === "bin" ? path.dirname(path.dirname(real)) : path.dirname(real);
33
+ const root = path.dirname(nodeDir);
34
+ if (path.basename(nodeDir) === "node") {
35
+ const manifest = JSON.parse(readFileSync(path.join(root, "alp-bundle.json"), "utf8"));
36
+ if (manifest?.name === "alp" && typeof manifest.version === "string") {
37
+ const app = path.dirname(root);
38
+ const current = path.join(app, "current");
39
+ info = { root, version: manifest.version, platform: String(manifest.platform ?? ""), app, ...existsSync(current) && samePath(current, root) ? { current } : {} };
40
+ }
41
+ }
42
+ } catch {
43
+ }
44
+ bundles.set(execPath, info);
45
+ return info;
46
+ }
47
+ function stablePath(file, { bundle = bundleInfo() } = {}) {
48
+ if (!bundle?.current) return file;
49
+ let real;
50
+ try {
51
+ real = realpathSync(file);
52
+ } catch {
53
+ return file;
54
+ }
55
+ const relative = path.relative(bundle.root, real);
56
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) return file;
57
+ return path.join(bundle.current, relative);
58
+ }
44
59
  function selfCommand(role, { script, args = [] }) {
45
- if (isPackaged()) return { command: process.execPath, args: [...roleArgs(role), ...args] };
60
+ roleArgs(role);
46
61
  return { command: process.execPath, args: [script, ...args] };
47
62
  }
48
63
  function entryCommand(entry, role, args = [], execPath = process.execPath, { scriptOnly = false } = {}) {
49
- if (scriptOnly || isScript(entry) || !(isExecutableName(entry) || isSelf(entry))) {
50
- if (isPackaged() && execPath === process.execPath) return { command: "node", args: [entry, ...args] };
51
- return { command: execPath, args: [entry, ...args] };
52
- }
64
+ if (scriptOnly || isScript(entry) || !isExecutableName(entry)) return { command: execPath, args: [entry, ...args] };
53
65
  return { command: entry, args: [...roleArgs(role), ...args] };
54
66
  }
55
67
  function scriptCommand(script, args = []) {
56
- if (isPackaged()) return { command: process.execPath, args: [script, ...args], env: { BUN_BE_BUN: "1" } };
57
68
  return { command: process.execPath, args: [script, ...args] };
58
69
  }
59
- function executablePath() {
60
- return isPackaged() ? process.execPath : void 0;
61
- }
62
70
  function selfEntry(script) {
63
- return isPackaged() ? process.execPath : script;
64
- }
65
- var sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
66
- var MARKER = ".alp-assets.json";
67
- function assetCacheDir(version, env = process.env) {
68
- if (!/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(version)) throw new TypeError(`Invalid ALP version for the asset cache: ${JSON.stringify(version)}`);
69
- const home = env.ALP_HOME ? path.resolve(env.ALP_HOME) : path.join(os.homedir(), ".alp");
70
- return path.join(home, "cache", version);
71
- }
72
- var manifestDigest = (assets) => sha256(Buffer.from(JSON.stringify(Object.keys(assets).sort().map((name) => [name, assets[name].sha256, assets[name].size]))));
73
- function assertAssetName(name) {
74
- if (!name || path.isAbsolute(name) || name.split(/[\\/]/).some((part) => part === ".." || part === "" || part === ".") || name === MARKER) throw new Error(`Invalid packaged asset name: ${JSON.stringify(name)}`);
75
- }
76
- function assertPrivate(directory) {
77
- const info = lstatSync(directory);
78
- if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`ALP asset cache is not a directory: ${directory}`);
79
- if (process.platform !== "win32" && (info.uid !== process.getuid?.() || (info.mode & 63) !== 0)) throw new Error(`ALP asset cache must be private to the current user (0700): ${directory}`);
80
- }
81
- function assertParent(directory) {
82
- const info = lstatSync(directory);
83
- if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`ALP asset cache parent is not a directory: ${directory}`);
84
- if (process.platform !== "win32" && (info.uid !== process.getuid?.() || (info.mode & 18) !== 0)) throw new Error(`ALP asset cache parent must belong to the current user and not be group- or world-writable: ${directory}`);
85
- }
86
- function extracted(directory, digest, assets) {
87
- try {
88
- if (JSON.parse(readFileSync(path.join(directory, MARKER), "utf8")).digest !== digest) return false;
89
- return Object.entries(assets).every(([name, asset]) => {
90
- const file = path.join(directory, name);
91
- const info = lstatSync(file);
92
- return info.isFile() && info.size === asset.size && sha256(readFileSync(file)) === asset.sha256;
93
- });
94
- } catch {
95
- return false;
96
- }
97
- }
98
- var STAGING = /^(.+)\.tmp-(\d+)-(\d+)$/;
99
- var STALE_MS = 60 * 60 * 1e3;
100
- var SWEEP_MIN_MS = 10 * 60 * 1e3;
101
- function sweepStaging(parent) {
102
- let names;
103
- try {
104
- names = readdirSync(parent);
105
- } catch {
106
- return;
107
- }
108
- for (const name of names) {
109
- const match = STAGING.exec(name);
110
- if (!match) continue;
111
- const pid = Number(match[2]);
112
- if (pid === process.pid) continue;
113
- const age = Date.now() - Number(match[3]);
114
- if (age < SWEEP_MIN_MS) continue;
115
- let alive = false;
116
- try {
117
- process.kill(pid, 0);
118
- alive = true;
119
- } catch (error) {
120
- alive = /** @type {any} */
121
- error?.code === "EPERM";
122
- }
123
- if (alive && age < STALE_MS) continue;
124
- try {
125
- rmSync(path.join(parent, name), { recursive: true, force: true });
126
- } catch {
127
- }
128
- }
129
- }
130
- function assetDir({ env = process.env, info = packagedInfo() } = {}) {
131
- if (!info) return void 0;
132
- const assets = info.assets ?? {};
133
- const directory = assetCacheDir(info.version, env);
134
- const digest = manifestDigest(assets);
135
- const key = `${directory}\0${digest}`;
136
- if (verified.has(key) && existsSync(path.join(directory, MARKER))) return directory;
137
- const result = extract(directory, digest, assets, info.version);
138
- verified.add(key);
139
- return result;
140
- }
141
- var verified = /* @__PURE__ */ new Set();
142
- function extract(directory, digest, assets, version) {
143
- const parent = path.dirname(directory);
144
- mkdirSync(parent, { recursive: true, mode: 448 });
145
- assertParent(parent);
146
- sweepStaging(parent);
147
- if (existsSync(directory)) {
148
- assertPrivate(directory);
149
- if (extracted(directory, digest, assets)) return directory;
150
- }
151
- const staging = `${directory}.tmp-${process.pid}-${Date.now()}`;
152
- mkdirSync(staging, { mode: 448 });
153
- try {
154
- for (const [name, asset] of Object.entries(assets)) {
155
- assertAssetName(name);
156
- const bytes = readFileSync(asset.path);
157
- if (bytes.length !== asset.size || sha256(bytes) !== asset.sha256) throw new Error(`Packaged asset ${name} does not match its manifest`);
158
- const target = path.join(staging, name);
159
- mkdirSync(path.dirname(target), { recursive: true, mode: 448 });
160
- writeFileSync(target, bytes, { mode: 384 });
161
- if (/(^|\/)terminal-owner(\.exe)?$/.test(name)) chmodSync(target, 448);
162
- }
163
- writeFileSync(path.join(staging, MARKER), JSON.stringify({ version, digest }), { mode: 384 });
164
- if (existsSync(directory)) {
165
- assertPrivate(directory);
166
- if (extracted(directory, digest, assets)) {
167
- rmSync(staging, { recursive: true, force: true });
168
- return directory;
169
- }
170
- rmSync(directory, { recursive: true, force: true });
171
- }
172
- renameSync(staging, directory);
173
- if (!extracted(directory, digest, assets)) throw new Error(`ALP asset cache ${directory} is incomplete after extraction`);
174
- } catch (error) {
175
- rmSync(staging, { recursive: true, force: true });
176
- if (existsSync(directory) && extracted(directory, digest, assets)) return directory;
177
- throw error;
178
- }
179
- return directory;
71
+ return stablePath(script);
180
72
  }
181
73
  export {
182
- EXECUTABLE_MARKER,
183
74
  ROLE_ARGS,
184
- assetCacheDir,
185
- assetDir,
75
+ bundleInfo,
186
76
  entryCommand,
187
- executablePath,
188
77
  isExecutableName,
189
- isPackaged,
190
78
  isScript,
191
- isSelf,
192
- packagedInfo,
193
- registerPackaged,
194
79
  samePath,
195
80
  scriptCommand,
196
81
  selfCommand,
197
- selfEntry
82
+ selfEntry,
83
+ stablePath
198
84
  };
@@ -0,0 +1,57 @@
1
+ /** Checks a pack.json against the files the pack holds. */
2
+ export function validatePack(id: any, manifest: any, files: any): any;
3
+ /**
4
+ * The packs ALP ships.
5
+ * @returns {Promise<Array<{ id: string, label: string, description: string, skills: string[], agents: string[], teams: string[], assign: Record<string, string[]>, permissions: Record<string, string> }>>}
6
+ */
7
+ export function listPacks(options?: {}): Promise<Array<{
8
+ id: string;
9
+ label: string;
10
+ description: string;
11
+ skills: string[];
12
+ agents: string[];
13
+ teams: string[];
14
+ assign: Record<string, string[]>;
15
+ permissions: Record<string, string>;
16
+ }>>;
17
+ /**
18
+ * Installs a pack into the library (`scope: 'library'`) or a project's .alp/ (`scope: 'project'`).
19
+ * Each entry is written to a temporary directory, checked (skills strictly, agent.json and team.json
20
+ * by their schemas), then renamed into place; an entry of that name already there is kept as is.
21
+ * `assign` (library only) adds the pack's suggested skills to roles in role-skills.json; the
22
+ * permissions a pack's agents need (an advisor's read-only cap) are added to that scope's settings
23
+ * only when the agent has no entry there, and a different entry is reported, never changed.
24
+ * @param {string} id
25
+ * @param {{ scope: 'library' | 'project', root?: string, library?: string, assign?: boolean, templates?: Record<string, string> }} options
26
+ */
27
+ export function installPack(id: string, { scope, root, library, assign, templates }?: {
28
+ scope: "library" | "project";
29
+ root?: string;
30
+ library?: string;
31
+ assign?: boolean;
32
+ templates?: Record<string, string>;
33
+ }): Promise<{
34
+ pack: string;
35
+ scope: "library" | "project";
36
+ installed: {
37
+ kind: string;
38
+ name: any;
39
+ path: string;
40
+ }[];
41
+ kept: {
42
+ kind: string;
43
+ name: any;
44
+ path: string;
45
+ }[];
46
+ assigned: string[];
47
+ permissions: {
48
+ set: never[];
49
+ kept: never[];
50
+ conflicts: never[];
51
+ };
52
+ }>;
53
+ /** Which of a pack's entries a scope already has: for listings. */
54
+ export function packStatus(pack: any, { root, library }?: {}): Promise<{
55
+ library: boolean;
56
+ project: boolean;
57
+ }>;
package/dist/packs.js ADDED
@@ -0,0 +1,247 @@
1
+ // packages/core/src/packs.js
2
+ import { chmod, lstat, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from "node:fs/promises";
3
+ import { randomUUID } from "node:crypto";
4
+ import path from "node:path";
5
+ import { moveFile } from "./atomic.js";
6
+ import { AlpError } from "./errors.js";
7
+ import { assertNoSymlinks } from "./safe-path.js";
8
+ import { seedLibrary } from "./library.js";
9
+ import { BASES, validatePermissions } from "./permissions.js";
10
+ import { validateSkill } from "./skill-validate.js";
11
+ import { shippedTemplateRoot } from "./template-path.js";
12
+ import { validateTeam } from "./teams.js";
13
+ import { validateAgentConfig } from "./validation.js";
14
+ var KINDS = ["skills", "agents", "teams"];
15
+ var PACK_KEYS = ["label", "description", ...KINDS, "assign", "permissions"];
16
+ var NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
17
+ var fail = (code, message) => {
18
+ throw new AlpError(code, message);
19
+ };
20
+ var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
21
+ async function shippedPackFiles({ templates } = {}) {
22
+ if (templates) return Object.fromEntries(Object.entries(templates).filter(([name]) => name.startsWith("packs/")));
23
+ const root = new URL("packs/", shippedTemplateRoot());
24
+ const files = {};
25
+ const walk = async (relative) => {
26
+ let entries;
27
+ try {
28
+ entries = await readdir(new URL(relative, root), { withFileTypes: true });
29
+ } catch (error) {
30
+ if (error.code === "ENOENT") return;
31
+ throw error;
32
+ }
33
+ for (const entry of entries) {
34
+ if (entry.isDirectory()) await walk(`${relative}${entry.name}/`);
35
+ else if (entry.isFile()) files[`packs/${relative}${entry.name}`] = await readFile(new URL(`${relative}${entry.name}`, root), "utf8");
36
+ }
37
+ };
38
+ await walk("");
39
+ return files;
40
+ }
41
+ function validatePack(id, manifest, files) {
42
+ const where = `packs/${id}/pack.json`;
43
+ const bad = (message) => fail("INVALID_PACK", `${where}: ${message}`);
44
+ if (!object(manifest)) bad("expected a JSON object");
45
+ for (const key of Object.keys(manifest)) if (!PACK_KEYS.includes(key)) bad(`unknown key '${key}'; expected ${PACK_KEYS.join(", ")}`);
46
+ for (const key of ["label", "description"]) if (typeof manifest[key] !== "string" || !manifest[key].trim()) bad(`${key} must be nonempty text`);
47
+ for (const kind of KINDS) {
48
+ const names = manifest[kind] ?? [];
49
+ if (!Array.isArray(names) || !names.every((name) => typeof name === "string" && NAME.test(name))) bad(`${kind} must list entry names`);
50
+ const main = { skills: "SKILL.md", agents: "AGENT.md", teams: "team.json" }[kind];
51
+ for (const name of names) if (files[`packs/${id}/${kind}/${name}/${main}`] === void 0) bad(`${kind} names '${name}', which has no ${kind}/${name}/${main}`);
52
+ }
53
+ if (!(manifest.skills?.length || manifest.agents?.length || manifest.teams?.length)) bad("a pack holds at least one skill, agent or team");
54
+ if (manifest.assign !== void 0) {
55
+ if (!object(manifest.assign)) bad("assign must map roles to skills");
56
+ for (const [role, skills] of Object.entries(manifest.assign)) {
57
+ if (!Array.isArray(skills) || !skills.every((skill) => (manifest.skills ?? []).includes(skill))) bad(`assign.${role} may name only this pack's skills`);
58
+ }
59
+ }
60
+ if (manifest.permissions !== void 0) {
61
+ if (!object(manifest.permissions)) bad("permissions must map agents to a base mode");
62
+ for (const [agent, base] of Object.entries(manifest.permissions)) {
63
+ if (!(manifest.agents ?? []).includes(agent)) bad(`permissions names '${agent}', which is not one of this pack's agents`);
64
+ if (!BASES.includes(base)) bad(`permissions.${agent} must be one of ${BASES.join(", ")}`);
65
+ }
66
+ }
67
+ return manifest;
68
+ }
69
+ async function listPacks(options = {}) {
70
+ const files = await shippedPackFiles(options);
71
+ const ids = [...new Set(Object.keys(files).filter((name) => /^packs\/[^/]+\/pack\.json$/.test(name)).map((name) => name.split("/")[1]))].sort();
72
+ return ids.map((id) => {
73
+ let manifest;
74
+ try {
75
+ manifest = JSON.parse(files[`packs/${id}/pack.json`]);
76
+ } catch (cause) {
77
+ throw new AlpError("INVALID_PACK", `packs/${id}/pack.json: ${cause.message}`, { cause });
78
+ }
79
+ validatePack(id, manifest, files);
80
+ return { id, label: manifest.label, description: manifest.description, skills: manifest.skills ?? [], agents: manifest.agents ?? [], teams: manifest.teams ?? [], assign: manifest.assign ?? {}, permissions: manifest.permissions ?? {} };
81
+ });
82
+ }
83
+ var present = (target) => lstat(target).then(() => true, (error) => {
84
+ if (error.code === "ENOENT") return false;
85
+ throw error;
86
+ });
87
+ async function writeJsonAtomic(file, value) {
88
+ await mkdir(path.dirname(file), { recursive: true });
89
+ const temporary = `${file}.${randomUUID().slice(0, 8)}.tmp`;
90
+ await writeFile(temporary, JSON.stringify(value, null, 2) + "\n");
91
+ await moveFile(temporary, file);
92
+ }
93
+ async function installPack(id, { scope, root, library, assign = false, templates } = {}) {
94
+ if (typeof id !== "string" || !NAME.test(id)) fail("INVALID_NAME", `'${id}' is not a pack name`);
95
+ const packs = await listPacks({ templates });
96
+ const pack = packs.find((candidate) => candidate.id === id) ?? fail("NOT_FOUND", `No pack '${id}'; packs are ${packs.map((candidate) => candidate.id).join(", ")}`);
97
+ if (scope !== "library" && scope !== "project") fail("INVALID_SCOPE", "Scope must be library or project");
98
+ if (scope === "library" && !library) fail("INVALID_SCOPE", "No library: ALP_HOME is not set");
99
+ if (scope === "project" && !root) fail("INVALID_SCOPE", "No project directory");
100
+ if (assign && scope !== "library") fail("INVALID_SCOPE", "Only the library assigns skills to roles (role-skills.json); in a project, name the skills in a project agent: alp agent edit <role> --project --skills a,b");
101
+ if (library) await seedLibrary(library, templates ? { templates } : {});
102
+ const given = scope === "library" ? library : path.resolve(root);
103
+ const scopeRoot = await realpath(given);
104
+ const inScope = scope === "library" ? "" : ".alp";
105
+ const base = path.join(scopeRoot, inScope);
106
+ const shown = (kind, name) => path.join(given, inScope, kind, name);
107
+ const guard = (relative) => assertNoSymlinks(scopeRoot, path.join(inScope, relative));
108
+ await guard(".");
109
+ for (const kind of KINDS) if (pack[kind].length) await guard(kind);
110
+ if (Object.keys(pack.permissions).length) await guard("settings.json");
111
+ if (assign) await guard("role-skills.json");
112
+ await mkdir(base, { recursive: true, ...scope === "library" ? { mode: 448 } : {} });
113
+ const files = await shippedPackFiles({ templates });
114
+ for (const file of Object.keys(files)) {
115
+ const parts = file.split("/");
116
+ if (parts.some((part) => !part || part === "." || part === ".." || !/^[\w.@+-]+$/.test(part))) fail("INVALID_PACK", `${file}: a pack file path must be plain relative names`);
117
+ }
118
+ const installed = [];
119
+ const kept = [];
120
+ for (const kind of KINDS) {
121
+ for (const name of pack[kind]) {
122
+ const target = path.join(base, kind, name);
123
+ await guard(kind);
124
+ if (await present(target)) {
125
+ kept.push({ kind, name, path: shown(kind, name) });
126
+ continue;
127
+ }
128
+ const prefix = `packs/${id}/${kind}/${name}/`;
129
+ const stagingName = `.alp-pack-${randomUUID().slice(0, 8)}.tmp`;
130
+ const stagingRoot = path.join(base, stagingName);
131
+ const staging = path.join(stagingRoot, name);
132
+ await guard(stagingName);
133
+ try {
134
+ await mkdir(stagingRoot, { recursive: false, ...scope === "library" ? { mode: 448 } : {} });
135
+ for (const [file, content] of Object.entries(files).filter(([file2]) => file2.startsWith(prefix))) {
136
+ const relative = file.slice(prefix.length);
137
+ const destination = path.join(staging, ...relative.split("/"));
138
+ await mkdir(path.dirname(destination), { recursive: true, ...scope === "library" ? { mode: 448 } : {} });
139
+ await writeFile(destination, content, { flag: "wx" });
140
+ if (process.platform !== "win32" && relative.startsWith("scripts/") && content.startsWith("#!")) await chmod(destination, 493);
141
+ }
142
+ if (kind === "skills") {
143
+ const { errors } = await validateSkill(staging, { mode: "strict" });
144
+ if (errors.length) fail("INVALID_PACK", `packs/${id}/skills/${name}: ${errors.map((finding) => finding.message).join("; ")}`);
145
+ }
146
+ if (kind === "agents") {
147
+ const config = await readFile(path.join(staging, "agent.json"), "utf8").then(JSON.parse, (error) => {
148
+ if (error.code === "ENOENT") return {};
149
+ throw error;
150
+ });
151
+ validateAgentConfig(config, `${prefix}agent.json`);
152
+ }
153
+ if (kind === "teams") validateTeam(JSON.parse(await readFile(path.join(staging, "team.json"), "utf8")), `${prefix}team.json`);
154
+ await guard(kind);
155
+ await guard(path.join(stagingName, name));
156
+ if (await present(target)) {
157
+ kept.push({ kind, name, path: shown(kind, name) });
158
+ continue;
159
+ }
160
+ await mkdir(path.dirname(target), { recursive: true });
161
+ await guard(kind);
162
+ await rename(staging, target);
163
+ installed.push({ kind, name, path: shown(kind, name) });
164
+ } finally {
165
+ await rm(stagingRoot, { recursive: true, force: true });
166
+ }
167
+ }
168
+ }
169
+ const permissions = { set: [], kept: [], conflicts: [] };
170
+ if (Object.keys(pack.permissions).length) {
171
+ const file = path.join(base, "settings.json");
172
+ await guard("settings.json");
173
+ const text = await readFile(file, "utf8").catch((error) => {
174
+ if (error.code === "ENOENT") return void 0;
175
+ throw error;
176
+ });
177
+ let settings = {};
178
+ if (text !== void 0) {
179
+ try {
180
+ settings = JSON.parse(text);
181
+ } catch (cause) {
182
+ throw new AlpError("INVALID_SETTINGS", `${file}: ${cause.message}`, { cause });
183
+ }
184
+ if (!object(settings)) fail("INVALID_SETTINGS", `${file}: expected a JSON object`);
185
+ }
186
+ const current = object(settings.permissions) ? settings.permissions : {};
187
+ const agents = object(current.agents) ? current.agents : {};
188
+ let changed = false;
189
+ for (const [agent, required] of Object.entries(pack.permissions)) {
190
+ if (!installed.some((entry) => entry.kind === "agents" && entry.name === agent)) {
191
+ if (!Object.hasOwn(agents, agent) || agents[agent] !== required) permissions.conflicts.push(`${agent}: your own ${agent} agent was kept, so its permissions were left as they are; the pack's ${agent} expects '${required}'`);
192
+ continue;
193
+ }
194
+ if (!Object.hasOwn(agents, agent)) {
195
+ agents[agent] = required;
196
+ permissions.set.push(`${agent}: ${required}`);
197
+ changed = true;
198
+ } else if (agents[agent] === required) permissions.kept.push(`${agent}: ${required}`);
199
+ else permissions.conflicts.push(`${agent}: ${file} gives '${agents[agent]}', the pack expects '${required}'; left as it is`);
200
+ }
201
+ if (changed) {
202
+ const next = { ...settings, permissions: { ...current, agents } };
203
+ validatePermissions(next.permissions, file);
204
+ await guard("settings.json");
205
+ await writeJsonAtomic(file, next);
206
+ }
207
+ }
208
+ const assigned = [];
209
+ if (assign && Object.keys(pack.assign).length) {
210
+ const file = path.join(base, "role-skills.json");
211
+ await guard("role-skills.json");
212
+ const text = await readFile(file, "utf8").catch((error) => {
213
+ if (error.code === "ENOENT") return "{}";
214
+ throw error;
215
+ });
216
+ let roles;
217
+ try {
218
+ roles = JSON.parse(text);
219
+ } catch (cause) {
220
+ throw new AlpError("INVALID_LIBRARY", `${file}: ${cause.message}; the pack was installed but no agent was given its skills`, { cause });
221
+ }
222
+ if (!object(roles)) fail("INVALID_LIBRARY", `${file}: expected an object of agent names to skill lists`);
223
+ for (const [role, skills] of Object.entries(pack.assign)) {
224
+ const list = Array.isArray(roles[role]) ? roles[role] : roles[role] = [];
225
+ for (const skill of skills) if (!list.includes(skill)) {
226
+ list.push(skill);
227
+ assigned.push(`${role}/${skill}`);
228
+ }
229
+ }
230
+ if (assigned.length) await writeJsonAtomic(file, roles);
231
+ }
232
+ return { pack: id, scope, installed, kept, assigned, permissions };
233
+ }
234
+ async function packStatus(pack, { root, library } = {}) {
235
+ const has = async (base) => {
236
+ if (!base) return false;
237
+ for (const kind of KINDS) for (const name of pack[kind]) if (!await present(path.join(base, kind, name))) return false;
238
+ return true;
239
+ };
240
+ return { library: await has(library), project: await has(root ? path.join(path.resolve(root), ".alp") : void 0) };
241
+ }
242
+ export {
243
+ installPack,
244
+ listPacks,
245
+ packStatus,
246
+ validatePack
247
+ };