@multileaf/ai-workflow 0.15.0 → 0.17.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 (58) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +19 -1
  3. package/dist/adapter.js +3 -3
  4. package/dist/artifact-paths.d.ts +16 -0
  5. package/dist/artifact-paths.js +51 -0
  6. package/dist/blocking-reasons.d.ts +1 -1
  7. package/dist/blocking-reasons.js +6 -0
  8. package/dist/completion-report.d.ts +17 -0
  9. package/dist/completion-report.js +42 -0
  10. package/dist/dashboard.js +7 -1
  11. package/dist/decision.d.ts +15 -0
  12. package/dist/decision.js +63 -0
  13. package/dist/eval/brief.d.ts +7 -0
  14. package/dist/eval/brief.js +28 -0
  15. package/dist/eval/generated.d.ts +17 -0
  16. package/dist/eval/generated.js +41 -0
  17. package/dist/eval/git.d.ts +13 -0
  18. package/dist/eval/git.js +70 -0
  19. package/dist/eval/monitor.d.ts +32 -0
  20. package/dist/eval/monitor.js +66 -0
  21. package/dist/eval/policy.d.ts +8 -0
  22. package/dist/eval/policy.js +9 -0
  23. package/dist/eval/proposals.d.ts +48 -0
  24. package/dist/eval/proposals.js +202 -0
  25. package/dist/eval/signals.d.ts +21 -0
  26. package/dist/eval/signals.js +155 -0
  27. package/dist/eval/types.d.ts +38 -0
  28. package/dist/eval/types.js +1 -0
  29. package/dist/eval/validate.d.ts +28 -0
  30. package/dist/eval/validate.js +66 -0
  31. package/dist/generator.d.ts +8 -1
  32. package/dist/generator.js +24 -1
  33. package/dist/recommendations.js +11 -0
  34. package/dist/risk-assess.d.ts +1 -1
  35. package/dist/risk-assess.js +26 -2
  36. package/dist/semantic.d.ts +19 -0
  37. package/dist/semantic.js +57 -0
  38. package/dist/services.d.ts +3 -0
  39. package/dist/telemetry.d.ts +6 -0
  40. package/dist/telemetry.js +14 -7
  41. package/dist/update.d.ts +42 -0
  42. package/dist/update.js +89 -0
  43. package/dist/workflow.js +583 -71
  44. package/docs/backlog.md +20 -2
  45. package/docs/continuation-inventory.md +24 -23
  46. package/docs/decision-model-evaluation.md +7 -2
  47. package/docs/opportunities/OPP-007-decision-findings-triage-scope-watch.md +1 -1
  48. package/docs/opportunities/OPP-008-embedding-covering-tests-judge-context.md +1 -1
  49. package/docs/semantic-mapping.md +9 -0
  50. package/package.json +1 -1
  51. package/resources/evals/scenarios/evaluator-draft-contract.yml +65 -0
  52. package/resources/package.yaml +2 -0
  53. package/resources/skills/research.md +64 -0
  54. package/resources/skills/resource-evaluator.md +24 -0
  55. package/resources/skills/review-judge-a.md +4 -0
  56. package/resources/skills/review-judge-b.md +4 -0
  57. package/resources/skills/review-refuter.md +4 -0
  58. package/resources/skills/ticket.md +1 -1
package/dist/generator.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { resolveGeneratedPath } from "./drift.js";
2
- export function generateProjectResources(profile, selected, write) {
2
+ export function generateProjectResources(profile, selected, write, semanticRetrieval = false) {
3
3
  const linterCommand = safeInlineValue(profile.quality.linter?.command);
4
4
  const formatterCommand = safeInlineValue(profile.quality.formatter?.command);
5
5
  const testCommands = [
@@ -22,6 +22,8 @@ export function generateProjectResources(profile, selected, write) {
22
22
  selected.includes("rules/architecture-policy"))
23
23
  write(resolveGeneratedPath("agents/project-context.md"), `# Project Context\n\nThis project uses ${profile.frameworks.map((framework) => (framework === "nextjs" ? "Next.js" : framework)).join(", ")}. Follow the detected project structure and existing framework conventions.\n`);
24
24
  if (selected.length > 0) {
25
+ if (semanticRetrieval)
26
+ write(resolveGeneratedPath("rules/semantic-retrieval.md"), "# Semantic Retrieval First\n\n- Prefer `aiw semantic query <terms>` over raw grep/rg when exploring unfamiliar context or locating relevant code; ranked semantic matches point at the most relevant chunks for a question.\n- Still use grep/rg (or git grep) for exact-string matches such as identifiers, error messages, and literal paths.\n- Semantic results are retrieval aids, never confirmed facts; verify against file contents before relying on them.\n");
25
27
  write(resolveGeneratedPath("context/project-profile.md"), `# Confirmed Project Profile\n\n- Languages: ${profile.runtime.languages.join(", ") || "none detected"}\n- Frameworks: ${profile.frameworks.join(", ") || "none detected"}\n- Package manager: ${profile.packageManager}\n- All generated content is in English.\n`);
26
28
  write(resolveGeneratedPath("context/root-context.md"), `# AI Workflow Project Context\n\nThis repository is managed by AI Workflow (\`.aiw/\` holds the neutral project state).\n\n- Languages: ${profile.runtime.languages.join(", ") || "none detected"}\n- Frameworks: ${profile.frameworks.join(", ") || "none detected"}\n- Package manager: ${profile.packageManager}${linterCommand ? `\n- Lint: \`${linterCommand}\`` : ""}${formatterCommand ? `\n- Format: \`${formatterCommand}\`` : ""}${uniqueTestCommands.map(({ scope, command }) => `\n- Tests (${scope}): \`${command}\``).join("")}\n\nBefore completing changes, run the project quality commands listed above. Follow installed AI Workflow skills, rules, and agents; the confirmed profile lives in \`.aiw/profile.yml\` and workflow evidence in \`.aiw/checkpoints/\`.\n\n## Context recovery (managed by AI Workflow)\n\nAfter any context compaction, reset, resume, or handoff: run \`aiw task status\`, read the stage artifacts this workflow declares under \`.aiw/generated/\`, and do not rely on compacted chat as the source of project state.\n`);
27
29
  write(resolveGeneratedPath("hooks/quality-check.md"), `# Quality Check Hook\n\nRun the available project quality commands before completion.${linterCommand ? `\n\n- Linter: \`${linterCommand}\`` : ""}${formatterCommand ? `\n- Formatter: \`${formatterCommand}\`` : ""}${uniqueTestCommands.map(({ scope, command }) => `\n- ${scope} tests: \`${command}\``).join("")}\n`);
@@ -37,3 +39,24 @@ function safeInlineValue(value) {
37
39
  .replace(/\s+/g, " ")
38
40
  .slice(0, 180);
39
41
  }
42
+ /**
43
+ * Materialize an approved evaluator proposal as a project-local resource with
44
+ * provenance frontmatter. Only the approve path may call this (REQ-004);
45
+ * output is always under generated/ via resolveGeneratedPath (REQ-006).
46
+ */
47
+ export function generateProposalResource(proposal, write) {
48
+ if (proposal.status !== "approved")
49
+ throw new Error(`Refusing to materialize proposal ${proposal.id}: only approved proposals can be materialized (status: ${proposal.status})`);
50
+ const directory = `${proposal.kind}s`;
51
+ write(resolveGeneratedPath(`${directory}/${proposal.signature}.md`), [
52
+ "---",
53
+ "provenance: aiw-evaluator",
54
+ `proposal: ${proposal.id}`,
55
+ "---",
56
+ "",
57
+ `# ${proposal.title}`,
58
+ "",
59
+ proposal.outline,
60
+ "",
61
+ ].join("\n"));
62
+ }
@@ -29,6 +29,17 @@ const CATALOG = [
29
29
  ? { evidence: projectEvidence(profile), confidence: 0.9 }
30
30
  : undefined,
31
31
  },
32
+ {
33
+ id: "bounded-research",
34
+ provider: "multileaf",
35
+ universal: true,
36
+ rationale: "Investigations that start from a single question (an error, a log signature, a migration implication) benefit from an evidence-first, budget-capped research contract with a durable artifact for later stages.",
37
+ permissions: [],
38
+ resources: local([{ type: "skills", id: "research" }]),
39
+ matches: (profile) => hasProjectSignals(profile)
40
+ ? { evidence: projectEvidence(profile), confidence: 0.85 }
41
+ : undefined,
42
+ },
32
43
  {
33
44
  id: "requirements-specification",
34
45
  provider: "multileaf",
@@ -45,7 +45,7 @@ export declare function assessRisk(changes: readonly ChangedFile[], options?: As
45
45
  export declare function collectWorkingTreeChanges(root: string): string[] | undefined;
46
46
  /** Deterministic covering-test probe: sibling *.test.* / *.spec.* variants. */
47
47
  export declare function hasCoveringTest(root: string, fs: FileSystem): (path: string) => boolean;
48
- export declare function runRiskAssess(args: string[], root: string, fs: FileSystem): Promise<CommandResult>;
48
+ export declare function runRiskAssess(args: string[], root: string, fs: FileSystem, embeddingProvider?: import("./semantic.js").EmbeddingProvider): Promise<CommandResult>;
49
49
  /**
50
50
  * Agent escalation (RDD parity): an agent may raise — never lower — the tier
51
51
  * citing one of the six high-risk items. Item must be 1..6; the reason is a
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import { execFileSync } from "node:child_process";
14
14
  import { join } from "node:path";
15
+ import { semanticCoveringEvidence } from "./semantic.js";
15
16
  export const RISK_CATEGORIES = [
16
17
  {
17
18
  item: 1,
@@ -187,7 +188,7 @@ function parseRiskAssessArgs(rest) {
187
188
  return undefined;
188
189
  return parsed;
189
190
  }
190
- export async function runRiskAssess(args, root, fs) {
191
+ export async function runRiskAssess(args, root, fs, embeddingProvider) {
191
192
  const jsonRequested = args.includes("--json");
192
193
  const parsed = parseRiskAssessArgs(args.filter((argument) => argument !== "--json"));
193
194
  if (!parsed)
@@ -206,7 +207,27 @@ export async function runRiskAssess(args, root, fs) {
206
207
  exitCode: 1,
207
208
  error: `git failed to enumerate changes${parsed.baseRef ? ` for --base-ref=${parsed.baseRef}` : ""}; verify the reference exists.`,
208
209
  };
209
- let assessment = assessRisk(changedPaths.map((path) => ({ path })), { hasCoveringTest: hasCoveringTest(root, fs) });
210
+ const siblingProbe = hasCoveringTest(root, fs);
211
+ let assessment = assessRisk(changedPaths.map((path) => ({ path })), {
212
+ hasCoveringTest: siblingProbe,
213
+ });
214
+ // OPP-008 REQ-001: retrieval can only prevent false `untested_regression`
215
+ // flags; tiers stay rule-based (REQ-002); undefined evidence keeps the
216
+ // deterministic floor byte-identical.
217
+ let coveringEvidence = [];
218
+ const untested = assessment.reasons
219
+ .filter((reason) => reason.code === "untested_regression" && reason.path)
220
+ .map((reason) => reason.path);
221
+ if (untested.length > 0) {
222
+ const evidence = await semanticCoveringEvidence(fs, join(root, ".aiw"), untested, embeddingProvider);
223
+ if (evidence && evidence.covering.length > 0) {
224
+ const covered = new Set(evidence.covering);
225
+ coveringEvidence = [...covered];
226
+ assessment = assessRisk(changedPaths.map((path) => ({ path })), {
227
+ hasCoveringTest: (path) => siblingProbe(path) || covered.has(path),
228
+ });
229
+ }
230
+ }
210
231
  if (parsed.escalateItem !== undefined && parsed.escalateReason !== undefined) {
211
232
  try {
212
233
  assessment = applyEscalation(assessment, parsed.escalateItem, parsed.escalateReason);
@@ -228,6 +249,7 @@ export async function runRiskAssess(args, root, fs) {
228
249
  reasons: assessment.reasons,
229
250
  changed_paths: assessment.changedPaths.length,
230
251
  risk_due: riskDue,
252
+ ...(coveringEvidence.length ? { covering_evidence: coveringEvidence } : {}),
231
253
  };
232
254
  if (parsed.ticket)
233
255
  envelope.ticket = parsed.ticket;
@@ -240,6 +262,8 @@ export async function runRiskAssess(args, root, fs) {
240
262
  const lines = [`risk: ${assessment.tier}`];
241
263
  for (const reason of assessment.reasons)
242
264
  lines.push(` - ${reason.code}${reason.path ? `: ${reason.path}` : reason.detail ? ` (${reason.detail})` : ""}`);
265
+ if (coveringEvidence.length)
266
+ lines.push(`covering: semantic-retrieval (${coveringEvidence.join(", ")})`);
243
267
  const next = nextCommand
244
268
  ? `risk due: yes -> ${nextCommand}`
245
269
  : nextAction
@@ -46,6 +46,8 @@ export declare function isExcludedIndexFile(file: string): boolean;
46
46
  export declare function parseSemanticMapping(raw: unknown): SemanticConfig;
47
47
  export declare function serializeSemanticConfig(config: SemanticConfig): string;
48
48
  export declare function loadSemanticConfig(fs: FileSystem, aiwPath: string): SemanticConfig | undefined;
49
+ /** FRIC-001: semantic retrieval is usable when mapping is enabled and an index exists. */
50
+ export declare function semanticRetrievalAvailable(fs: FileSystem, aiwPath: string): boolean;
49
51
  export declare function parseSemanticConfig(text: string): SemanticConfig;
50
52
  type FetchLike = (url: string, init?: RequestInit) => Promise<Response>;
51
53
  export declare function createOllamaEmbeddingProvider(config: SemanticConfig, fetchImpl?: FetchLike, env?: Readonly<Record<string, string | undefined>>): EmbeddingProvider;
@@ -56,4 +58,21 @@ export declare function serializeSemanticIndex(index: SemanticIndex): string;
56
58
  export declare function parseSemanticIndex(text: string): SemanticIndex;
57
59
  export declare function querySemanticIndex(index: SemanticIndex, query: string, provider: EmbeddingProvider, config: SemanticConfig): Promise<SemanticMatch[]>;
58
60
  export declare function rerankSemanticMatches(matches: SemanticMatch[], query: string, reranker: DecisionReranker): Promise<RerankOutcome>;
61
+ /** OPP-008: path-semantics-only query for covering tests (no symbol parsing). */
62
+ export declare function buildCoveringTestQuery(path: string): string;
63
+ export type CoveringEvidence = {
64
+ covering: string[];
65
+ degraded: boolean;
66
+ };
67
+ /**
68
+ * OPP-008 REQ-001: retrieval-aided covering-test detection. `undefined` keeps
69
+ * the deterministic sibling heuristic byte-identical (no config/index).
70
+ * Provider failures degrade to empty coverage (REQ-004: fail safe).
71
+ */
72
+ export declare function semanticCoveringEvidence(fs: FileSystem, aiwPath: string, paths: string[], provider?: EmbeddingProvider): Promise<CoveringEvidence | undefined>;
73
+ /** OPP-008 REQ-003: diff first, retrieved chunks fill the remaining budget, labeled as aids. */
74
+ export declare function renderJudgeContext(diff: string, chunks: {
75
+ file: string;
76
+ excerpt: string;
77
+ }[], budget: number): string;
59
78
  export {};
package/dist/semantic.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { parseDocument } from "yaml";
2
+ import { join } from "path";
2
3
  import { loadSettings } from "./settings.js";
3
4
  export const SEMANTIC_CONFIG_PATH = "semantic.yml";
4
5
  export const SEMANTIC_INDEX_PATH = "semantic/index.json";
@@ -83,6 +84,11 @@ export function loadSemanticConfig(fs, aiwPath) {
83
84
  return undefined;
84
85
  return parseSemanticConfig(fs.read(configPath));
85
86
  }
87
+ /** FRIC-001: semantic retrieval is usable when mapping is enabled and an index exists. */
88
+ export function semanticRetrievalAvailable(fs, aiwPath) {
89
+ const config = loadSemanticConfig(fs, aiwPath);
90
+ return config?.enabled === true && fs.exists(join(aiwPath, SEMANTIC_INDEX_PATH));
91
+ }
86
92
  function parseSemanticDocument(text) {
87
93
  const document = parseDocument(text);
88
94
  const node = document.get("semantic");
@@ -273,3 +279,54 @@ export async function rerankSemanticMatches(matches, query, reranker) {
273
279
  changedPositions += 1;
274
280
  return { matches: reranked, changedPositions };
275
281
  }
282
+ /** OPP-008: path-semantics-only query for covering tests (no symbol parsing). */
283
+ export function buildCoveringTestQuery(path) {
284
+ const generic = new Set(["src", "lib", "app", "index", "main", "test", "tests", "spec"]);
285
+ const terms = path
286
+ .split(/[/.-]/)
287
+ .filter((segment) => segment && !generic.has(segment.toLowerCase()));
288
+ return `tests exercising ${terms.join(" ") || path}`;
289
+ }
290
+ const TEST_FILE_PATTERN = /(\.test\.|\.spec\.|(^|\/)tests?\/)/;
291
+ /**
292
+ * OPP-008 REQ-001: retrieval-aided covering-test detection. `undefined` keeps
293
+ * the deterministic sibling heuristic byte-identical (no config/index).
294
+ * Provider failures degrade to empty coverage (REQ-004: fail safe).
295
+ */
296
+ export async function semanticCoveringEvidence(fs, aiwPath, paths, provider) {
297
+ const config = loadSemanticConfig(fs, aiwPath);
298
+ if (!config?.enabled)
299
+ return undefined;
300
+ const indexPath = join(aiwPath, SEMANTIC_INDEX_PATH);
301
+ if (!fs.exists(indexPath))
302
+ return undefined;
303
+ try {
304
+ const index = parseSemanticIndex(fs.read(indexPath));
305
+ const embed = provider ?? createOllamaEmbeddingProvider(config);
306
+ if (!(await embed.available()))
307
+ return { covering: [], degraded: true };
308
+ const covering = [];
309
+ for (const path of paths) {
310
+ const matches = await querySemanticIndex(index, buildCoveringTestQuery(path), embed, config);
311
+ if (matches.some((match) => TEST_FILE_PATTERN.test(match.file)))
312
+ covering.push(path);
313
+ }
314
+ return { covering, degraded: false };
315
+ }
316
+ catch {
317
+ return { covering: [], degraded: true };
318
+ }
319
+ }
320
+ /** OPP-008 REQ-003: diff first, retrieved chunks fill the remaining budget, labeled as aids. */
321
+ export function renderJudgeContext(diff, chunks, budget) {
322
+ const lines = [diff];
323
+ let used = diff.length;
324
+ for (const chunk of chunks) {
325
+ const block = `\n- ${chunk.file} (context aid (retrieval — not a confirmed fact)): ${chunk.excerpt}`;
326
+ if (used + block.length > budget)
327
+ break;
328
+ lines.push(block);
329
+ used += block.length;
330
+ }
331
+ return lines.join("");
332
+ }
@@ -1,4 +1,5 @@
1
1
  import type { ProjectProfile } from "./profile.js";
2
+ import type { ShellRunner } from "./eval/scenarios.js";
2
3
  import type { EmbeddingProvider } from "./semantic.js";
3
4
  import type { ProjectScan } from "./scanner.js";
4
5
  import type { CapabilityRecommendation } from "./recommendations.js";
@@ -40,6 +41,8 @@ export interface WorkflowDependencies {
40
41
  embeddingProvider?: EmbeddingProvider;
41
42
  aiProvider?: AiProvider;
42
43
  decisionProvider?: DecisionProvider;
44
+ /** Overrides shell execution for git signal collection in `aiw evaluate`. */
45
+ runShell?: ShellRunner;
43
46
  }
44
47
  export interface WorkflowService {
45
48
  execute(args: string[], root: string, fs: FileSystem): Promise<CommandResult>;
@@ -16,6 +16,12 @@ export interface TelemetryClient {
16
16
  export declare const DEFAULT_TELEMETRY_CONFIG: TelemetryConfig;
17
17
  export declare const TELEMETRY_CONSENT_PROMPT = "Enable anonymous telemetry? Each event contains only the command name and its outcome (success or failure) - never arguments, file paths, or file contents. [y/N] ";
18
18
  export declare function offerTelemetryConsent(fs: FileSystem, aiwPath: string, answer: (question: string) => Promise<string>): Promise<boolean>;
19
+ export declare function isTelemetryConfigured(fs: FileSystem, aiwPath: string): boolean;
20
+ /** FRIC-004: prompt once (interactive only) when telemetry consent is unset. */
21
+ export declare function maybeOfferTelemetryConsent(fs: FileSystem, aiwPath: string, isTty: boolean, answer: (question: string) => Promise<string>): Promise<{
22
+ prompted: boolean;
23
+ enabled: boolean;
24
+ }>;
19
25
  export declare function parseTelemetryMapping(raw: unknown): TelemetryConfig;
20
26
  export declare function serializeTelemetryMapping(config: TelemetryConfig): unknown;
21
27
  export declare function loadTelemetryConfig(fs: FileSystem, aiwPath: string): TelemetryConfig;
package/dist/telemetry.js CHANGED
@@ -20,6 +20,18 @@ export async function offerTelemetryConsent(fs, aiwPath, answer) {
20
20
  }));
21
21
  return enabled;
22
22
  }
23
+ export function isTelemetryConfigured(fs, aiwPath) {
24
+ const settings = loadSettings(fs, aiwPath);
25
+ return ((settings !== undefined && "telemetry" in settings) || fs.exists(`${aiwPath}/telemetry.yml`));
26
+ }
27
+ /** FRIC-004: prompt once (interactive only) when telemetry consent is unset. */
28
+ export async function maybeOfferTelemetryConsent(fs, aiwPath, isTty, answer) {
29
+ if (isTelemetryConfigured(fs, aiwPath))
30
+ return { prompted: false, enabled: loadTelemetryConfig(fs, aiwPath).enabled };
31
+ if (!isTty)
32
+ return { prompted: false, enabled: false };
33
+ return { prompted: true, enabled: await offerTelemetryConsent(fs, aiwPath, answer) };
34
+ }
23
35
  const TELEMETRY_COMMANDS = new Set([
24
36
  "adr",
25
37
  "audit-package",
@@ -159,10 +171,7 @@ export async function recordConfiguredTelemetry(fs, aiwPath, client, command, re
159
171
  if (!client) {
160
172
  try {
161
173
  const config = loadTelemetryConfig(fs, aiwPath);
162
- const settings = loadSettings(fs, aiwPath);
163
- const configured = (settings !== undefined && "telemetry" in settings) ||
164
- fs.exists(`${aiwPath}/telemetry.yml`);
165
- if (configured) {
174
+ if (isTelemetryConfigured(fs, aiwPath)) {
166
175
  const event = createTelemetryEvent(command, result, config);
167
176
  if (event)
168
177
  appendTelemetryBuffer(fs, aiwPath, event);
@@ -175,9 +184,7 @@ export async function recordConfiguredTelemetry(fs, aiwPath, client, command, re
175
184
  }
176
185
  try {
177
186
  const config = loadTelemetryConfig(fs, aiwPath);
178
- const settings = loadSettings(fs, aiwPath);
179
- const configured = (settings !== undefined && "telemetry" in settings) || fs.exists(`${aiwPath}/telemetry.yml`);
180
- if (!configured)
187
+ if (!isTelemetryConfigured(fs, aiwPath))
181
188
  return;
182
189
  const event = createTelemetryEvent(command, result, config);
183
190
  if (event)
@@ -0,0 +1,42 @@
1
+ import type { FileSystem } from "./types.js";
2
+ import type { Target } from "./types.js";
3
+ import { type OwnedFile } from "./ownership.js";
4
+ export type UpdatePlan = {
5
+ updated: {
6
+ path: string;
7
+ content: string;
8
+ }[];
9
+ conflicts: string[];
10
+ newIds: string[];
11
+ unchanged: number;
12
+ install: {
13
+ type: string;
14
+ id: string;
15
+ content: string;
16
+ }[];
17
+ };
18
+ export type UpdatePlanInput = {
19
+ fs: FileSystem;
20
+ root: string;
21
+ aiw: string;
22
+ target: Target;
23
+ add: string[];
24
+ /** Catalog contents by `type/id` (injected for tests; defaults to the bundled package). */
25
+ bundle?: Map<string, {
26
+ type: string;
27
+ id: string;
28
+ content: string;
29
+ }>;
30
+ /** Personalizer for desired bytes (defaults to the raw catalog content). */
31
+ personalize?: (type: string, id: string, content: string) => string;
32
+ /** Render path resolver per target (defaults to bundled path mapping). */
33
+ renderPath?: (type: string, id: string, target: Target) => string;
34
+ };
35
+ /**
36
+ * UPD-001: diff installed bundled resources against the catalog using the
37
+ * ownership checksum as the drift oracle. `--add` ids are validated against
38
+ * the catalog and appended additively.
39
+ */
40
+ export declare function computeUpdatePlan(input: UpdatePlanInput): UpdatePlan;
41
+ /** Refreshed ownership entries after applying an update (checksums recomputed). */
42
+ export declare function refreshOwnershipChecksums(owned: OwnedFile[], fs: FileSystem, root: string): OwnedFile[];
package/dist/update.js ADDED
@@ -0,0 +1,89 @@
1
+ import { join } from "path";
2
+ import { parseOwnership, createOwnedFile } from "./ownership.js";
3
+ import { loadBundledResources } from "./bundled-resources.js";
4
+ import { checksumPackage } from "./package-integrity.js";
5
+ import { resourcesForCapabilities } from "./recommendations.js";
6
+ /**
7
+ * UPD-001: diff installed bundled resources against the catalog using the
8
+ * ownership checksum as the drift oracle. `--add` ids are validated against
9
+ * the catalog and appended additively.
10
+ */
11
+ export function computeUpdatePlan(input) {
12
+ const { fs, root, aiw, target, add } = input;
13
+ const ownershipPath = join(aiw, "ownership.yml");
14
+ const owned = fs.exists(ownershipPath) ? parseOwnership(fs.read(ownershipPath)) : [];
15
+ const bundle = input.bundle ?? new Map(loadBundledResources(target).map((r) => [`${r.type}/${r.id}`, r]));
16
+ const personalize = input.personalize ?? ((_t, _i, content) => content);
17
+ // Unknown --add ids fail closed with the available ids.
18
+ const catalogResourceIds = [...bundle.keys()];
19
+ const catalogCapabilityResources = new Set(resourcesForCapabilities([...catalogResourceIds]).map((r) => `${r.type}/${r.id}`));
20
+ const addKeys = add.map((id) => (id.includes("/") ? id : capabilityResourceKey(id, bundle)));
21
+ for (const key of addKeys)
22
+ if (!bundle.has(key) && !catalogCapabilityResources.has(key))
23
+ throw new Error(`Unknown resource id: ${key}. Available: ${catalogResourceIds.sort().join(", ")}`);
24
+ const installedKeys = new Set();
25
+ const conflicts = [];
26
+ const updated = [];
27
+ let unchanged = 0;
28
+ for (const file of owned) {
29
+ if (file.resourceType === undefined || file.resourceId === undefined) {
30
+ unchanged += 1; // supporting/legacy entries are never touched by update
31
+ continue;
32
+ }
33
+ const key = `${file.resourceType}/${file.resourceId}`;
34
+ installedKeys.add(key);
35
+ const resource = bundle.get(key);
36
+ if (!resource) {
37
+ unchanged += 1; // resource no longer in the catalog: leave untouched
38
+ continue;
39
+ }
40
+ const filePath = join(root, file.path);
41
+ if (!fs.exists(filePath)) {
42
+ unchanged += 1;
43
+ continue;
44
+ }
45
+ const bytes = fs.read(filePath);
46
+ const drifted = `sha256-${checksumPackage(bytes)}` !== file.checksum;
47
+ if (drifted) {
48
+ conflicts.push(file.path);
49
+ continue;
50
+ }
51
+ const desired = personalize(resource.type, resource.id, resource.content);
52
+ if (desired === bytes)
53
+ unchanged += 1;
54
+ else
55
+ updated.push({ path: file.path, content: desired });
56
+ }
57
+ const newIds = [];
58
+ const install = [];
59
+ for (const key of catalogResourceIds) {
60
+ const [type, id] = key.split("/");
61
+ if (installedKeys.has(key))
62
+ continue;
63
+ newIds.push(key);
64
+ if (addKeys.includes(key))
65
+ install.push({ type, id, content: personalize(type, id, bundle.get(key).content) });
66
+ }
67
+ return { updated, conflicts, newIds, unchanged, install };
68
+ }
69
+ function capabilityResourceKey(capabilityId, bundle) {
70
+ const resources = resourcesForCapabilities([capabilityId]);
71
+ for (const resource of resources)
72
+ if (bundle.has(`${resource.type}/${resource.id}`))
73
+ return `${resource.type}/${resource.id}`;
74
+ return capabilityId;
75
+ }
76
+ /** Refreshed ownership entries after applying an update (checksums recomputed). */
77
+ export function refreshOwnershipChecksums(owned, fs, root) {
78
+ return owned.map((file) => {
79
+ const filePath = join(root, file.path);
80
+ if (!fs.exists(filePath))
81
+ return file;
82
+ return createOwnedFile(file.path, fs.read(filePath), {
83
+ kind: file.kind,
84
+ target: file.target,
85
+ resourceType: file.resourceType,
86
+ resourceId: file.resourceId,
87
+ });
88
+ });
89
+ }