@inneranimalmedia/primetech-procedures 0.0.0-stage → 2.6.18

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 (76) hide show
  1. package/.codex-plugin/plugin.json +39 -0
  2. package/LICENSE +110 -0
  3. package/README.md +181 -2
  4. package/agents/openai.yaml +6 -0
  5. package/agentsam.package.json +80 -0
  6. package/assets/architect-icon.svg +10 -0
  7. package/assets/primetech-design-studio.svg +7 -0
  8. package/companion.json +40 -0
  9. package/package.json +56 -4
  10. package/plugin.README.md +37 -0
  11. package/plugin.json +43 -0
  12. package/procedures/arch.assembly.calculate/procedure.json +83 -0
  13. package/procedures/cad.motor-bearing-end-plate/README.md +21 -0
  14. package/procedures/cad.motor-bearing-end-plate/build_freecad.py +514 -0
  15. package/procedures/cad.motor-bearing-end-plate/finalize_bundle.py +26 -0
  16. package/procedures/cad.motor-bearing-end-plate/generate_assets.py +284 -0
  17. package/procedures/cad.motor-bearing-end-plate/generate_toolpaths.py +715 -0
  18. package/procedures/cad.motor-bearing-end-plate/package_artifacts.py +154 -0
  19. package/procedures/cad.motor-bearing-end-plate/parameters.json +51 -0
  20. package/procedures/cad.motor-bearing-end-plate/procedure.json +101 -0
  21. package/procedures/cad.motor-bearing-end-plate/render_preview.py +98 -0
  22. package/procedures/cad.motor-bearing-end-plate/run.py +214 -0
  23. package/procedures/cad.motor-bearing-end-plate/test_generate_toolpaths.py +50 -0
  24. package/procedures/media.asset.preflight/procedure.json +85 -0
  25. package/procedures/media.image.optimize-asset/procedure.json +102 -0
  26. package/procedures/primetech.assets.package/procedure.json +63 -0
  27. package/procedures/primetech.design-system.package/procedure.json +58 -0
  28. package/procedures/primetech.ebook.package/procedure.json +53 -0
  29. package/procedures/primetech.icon-family.build/procedure.json +101 -0
  30. package/procedures/primetech.production-board.manage/procedure.json +156 -0
  31. package/procedures/primetech.sprite-atlas.build/procedure.json +86 -0
  32. package/procedures/primetech.typeface.package/procedure.json +61 -0
  33. package/procedures/primetech.visuals.compare/procedure.json +74 -0
  34. package/procedures/repo.asset.inventory/procedure.json +65 -0
  35. package/procedures/repo.asset.inventory/run.py +116 -0
  36. package/procedures/repo.asset.inventory/run.sh +11 -0
  37. package/procedures/repo.git.status/procedure.json +58 -0
  38. package/procedures/repo.git.status/run.sh +10 -0
  39. package/profiles/PRIMETECH_PROCEDURE_ENGINEER.md +25 -0
  40. package/scripts/generate-procedures.py +112 -0
  41. package/scripts/generate-skills.py +425 -0
  42. package/scripts/package-openai-plugin.py +94 -0
  43. package/skills/primetech-brand-kit/SKILL.md +40 -0
  44. package/skills/primetech-brand-kit/agentsam.skill.json +64 -0
  45. package/skills/primetech-character-sprites/SKILL.md +40 -0
  46. package/skills/primetech-character-sprites/agentsam.skill.json +64 -0
  47. package/skills/primetech-creative-delivery/SKILL.md +39 -0
  48. package/skills/primetech-creative-delivery/agentsam.skill.json +57 -0
  49. package/skills/primetech-design-systems/SKILL.md +43 -0
  50. package/skills/primetech-design-systems/agentsam.skill.json +57 -0
  51. package/skills/primetech-digital-publishing/SKILL.md +39 -0
  52. package/skills/primetech-digital-publishing/agentsam.skill.json +52 -0
  53. package/skills/primetech-iconography/SKILL.md +40 -0
  54. package/skills/primetech-iconography/agentsam.skill.json +53 -0
  55. package/skills/primetech-type-design/SKILL.md +40 -0
  56. package/skills/primetech-type-design/agentsam.skill.json +53 -0
  57. package/skills/primetech-ui-ux-prototypes/SKILL.md +43 -0
  58. package/skills/primetech-ui-ux-prototypes/agentsam.skill.json +64 -0
  59. package/skills/primetech-visual-qa/SKILL.md +39 -0
  60. package/skills/primetech-visual-qa/agentsam.skill.json +56 -0
  61. package/src/creative/asset-package.js +42 -0
  62. package/src/creative/design-system.js +107 -0
  63. package/src/creative/ebook.js +88 -0
  64. package/src/creative/icon-family.js +125 -0
  65. package/src/creative/index.d.ts +157 -0
  66. package/src/creative/index.js +7 -0
  67. package/src/creative/paths.js +64 -0
  68. package/src/creative/sprite-atlas.js +100 -0
  69. package/src/creative/typeface.js +154 -0
  70. package/src/creative/visual-qa.js +88 -0
  71. package/src/index.d.ts +160 -0
  72. package/src/index.js +656 -0
  73. package/src/production-board.d.ts +103 -0
  74. package/src/production-board.js +181 -0
  75. package/src/skills.d.ts +48 -0
  76. package/src/skills.js +101 -0
@@ -0,0 +1,103 @@
1
+ /** TypeScript declarations for PrimeTech's resumable production board. */
2
+ export type ProductionGenerationStatus = 'queued' | 'running' | 'needs_review' | 'completed' | 'failed' | 'cancelled';
3
+ export interface ProductionBoardProject {
4
+ id: string | null;
5
+ title: string;
6
+ objective: string;
7
+ brief: string;
8
+ tags: string[];
9
+ }
10
+ export interface ProductionGenerationArtifact { ref: string; [key: string]: unknown; }
11
+ export interface ProductionGenerationQualityCheck { name: string; status: 'pass' | 'fail' | 'warn'; [key: string]: unknown; }
12
+ export interface ProductionBoardGeneration {
13
+ id: string;
14
+ kind: string;
15
+ status: ProductionGenerationStatus;
16
+ brief: string;
17
+ prompt: string;
18
+ sourceRefs: string[];
19
+ idempotencyKey: string | null;
20
+ attempt: number;
21
+ artifacts: ProductionGenerationArtifact[];
22
+ qualityChecks: ProductionGenerationQualityCheck[];
23
+ events: Array<{ type: string; at: string; [key: string]: unknown }>;
24
+ startedAt: string;
25
+ updatedAt: string;
26
+ completedAt?: string | null;
27
+ receipt?: Record<string, unknown>;
28
+ error?: { code: string; message: string };
29
+ retryable?: boolean;
30
+ }
31
+ export interface ProductionBoard {
32
+ schema: 'agentsam.primetech.production-board.v1';
33
+ id: string;
34
+ project: ProductionBoardProject;
35
+ status: string;
36
+ revision: number;
37
+ generations: ProductionBoardGeneration[];
38
+ createdAt: string;
39
+ updatedAt: string;
40
+ }
41
+ export interface ProductionBoardSummary {
42
+ boardId: string;
43
+ title: string;
44
+ status: string;
45
+ revision: number;
46
+ generationCount: number;
47
+ updatedAt: string;
48
+ }
49
+ export interface ProductionBoardActionResult {
50
+ ok: true;
51
+ boardId?: string;
52
+ revision?: number;
53
+ status?: string;
54
+ path?: string;
55
+ board?: ProductionBoard;
56
+ generationId?: string;
57
+ generation?: ProductionBoardGeneration;
58
+ qualityPassed?: boolean;
59
+ retryable?: boolean;
60
+ idempotentReplay?: boolean;
61
+ resumableCount?: number;
62
+ resumable?: ProductionBoardGeneration[];
63
+ }
64
+ export interface ProductionBoardListResult { ok: true; count: number; boards: ProductionBoardSummary[]; }
65
+ export interface CreateProductionBoardInput {
66
+ projectRoot: string;
67
+ title: string;
68
+ objective: string;
69
+ brief?: string;
70
+ projectId?: string | null;
71
+ tags?: string[];
72
+ }
73
+ export interface ProductionBoardIdInput { projectRoot: string; boardId: string; }
74
+ export interface BeginProductionGenerationInput extends ProductionBoardIdInput {
75
+ generationId?: string | null;
76
+ idempotencyKey?: string | null;
77
+ kind: string;
78
+ brief: string;
79
+ prompt?: string;
80
+ sourceRefs?: string[];
81
+ expectedRevision?: number | null;
82
+ }
83
+ export interface CompleteProductionGenerationInput extends ProductionBoardIdInput {
84
+ generationId: string;
85
+ artifacts: ProductionGenerationArtifact[];
86
+ qualityChecks: ProductionGenerationQualityCheck[];
87
+ receipt?: Record<string, unknown>;
88
+ expectedRevision?: number | null;
89
+ }
90
+ export interface FailProductionGenerationInput extends ProductionBoardIdInput {
91
+ generationId: string;
92
+ error: { code: string; message?: string };
93
+ retryable?: boolean;
94
+ expectedRevision?: number | null;
95
+ }
96
+ export function createProductionBoard(input: CreateProductionBoardInput): Promise<ProductionBoardActionResult & { boardId: string; revision: number; status: string; path: string; board: ProductionBoard }>;
97
+ export function getProductionBoard(input: ProductionBoardIdInput): Promise<ProductionBoardActionResult & { boardId: string; revision: number; status: string; board: ProductionBoard }>;
98
+ export function listProductionBoards(input: { projectRoot: string }): Promise<ProductionBoardListResult>;
99
+ export function beginGeneration(input: BeginProductionGenerationInput): Promise<ProductionBoardActionResult & { boardId: string; revision: number; status: string; generationId: string; generation: ProductionBoardGeneration }>;
100
+ export function completeGeneration(input: CompleteProductionGenerationInput): Promise<ProductionBoardActionResult & { boardId: string; revision: number; status: string; generationId: string; qualityPassed: boolean; generation: ProductionBoardGeneration }>;
101
+ export function failGeneration(input: FailProductionGenerationInput): Promise<ProductionBoardActionResult & { boardId: string; revision: number; status: string; generationId: string; retryable: boolean; generation: ProductionBoardGeneration }>;
102
+ export function resumeProductionBoard(input: ProductionBoardIdInput): Promise<ProductionBoardActionResult & { boardId: string; revision: number; status: string; resumableCount: number; resumable: ProductionBoardGeneration[] }>;
103
+ export const productionBoardContract: { readonly schema: 'agentsam.primetech.production-board.v1'; readonly generationStatuses: readonly ProductionGenerationStatus[] };
@@ -0,0 +1,181 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import { ensureProjectDirectory, safeSlug, writeJsonAtomic } from './creative/paths.js';
5
+
6
+ const BOARD_SCHEMA = 'agentsam.primetech.production-board.v1';
7
+ const GENERATION_STATUSES = new Set(['queued', 'running', 'needs_review', 'completed', 'failed', 'cancelled']);
8
+
9
+ function id(prefix) { return `${prefix}_${crypto.randomBytes(12).toString('hex')}`; }
10
+ function boardPath(root, boardId) {
11
+ if (typeof boardId !== 'string' || !/^ptb_[a-f0-9]{24}$/.test(boardId)) throw new Error('production_board_id_invalid');
12
+ return path.join(root, 'boards', `${boardId}.json`);
13
+ }
14
+
15
+ async function withBoardLock(filePath, operation) {
16
+ const lockPath = `${filePath}.lock`;
17
+ let handle;
18
+ try {
19
+ handle = await fs.open(lockPath, 'wx', 0o600);
20
+ } catch (error) {
21
+ if (error?.code === 'EEXIST') throw new Error('production_board_locked');
22
+ throw error;
23
+ }
24
+ try { return await operation(); }
25
+ finally {
26
+ await handle?.close().catch(() => {});
27
+ await fs.rm(lockPath, { force: true }).catch(() => {});
28
+ }
29
+ }
30
+
31
+ async function readBoardFile(filePath) {
32
+ let board;
33
+ try { board = JSON.parse(await fs.readFile(filePath, 'utf8')); }
34
+ catch (error) { if (error?.code === 'ENOENT') throw new Error('production_board_not_found'); throw new Error('production_board_corrupt'); }
35
+ if (board.schema !== BOARD_SCHEMA || !Array.isArray(board.generations) || !Number.isInteger(board.revision)) throw new Error('production_board_corrupt');
36
+ return board;
37
+ }
38
+
39
+ async function saveBoard(filePath, board, expectedRevision) {
40
+ if (expectedRevision !== undefined && expectedRevision !== null && expectedRevision !== board.revision) throw new Error(`production_board_revision_conflict:${board.revision}`);
41
+ board.revision += 1;
42
+ board.updatedAt = new Date().toISOString();
43
+ await writeJsonAtomic(filePath, board);
44
+ return board;
45
+ }
46
+
47
+ export async function createProductionBoard({ projectRoot, title, objective, brief = '', projectId = null, tags = [] } = {}) {
48
+ if (typeof title !== 'string' || !title.trim() || title.length > 160) throw new Error('production_board_title_invalid');
49
+ if (typeof objective !== 'string' || !objective.trim() || objective.length > 1200) throw new Error('production_board_objective_required');
50
+ if (typeof brief !== 'string' || brief.length > 12000) throw new Error('production_board_brief_invalid');
51
+ if (!Array.isArray(tags) || tags.some(tag => typeof tag !== 'string' || tag.length > 48)) throw new Error('production_board_tags_invalid');
52
+ const root = await ensureProjectDirectory(projectRoot, '.agentsam/primetech');
53
+ const boardId = id('ptb');
54
+ const now = new Date().toISOString();
55
+ const board = {
56
+ schema: BOARD_SCHEMA,
57
+ id: boardId,
58
+ project: { id: projectId, title: title.trim(), objective: objective.trim(), brief, tags },
59
+ status: 'active',
60
+ revision: 1,
61
+ generations: [],
62
+ createdAt: now,
63
+ updatedAt: now,
64
+ };
65
+ const filePath = boardPath(path.join(root, 'boards'), boardId);
66
+ await fs.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
67
+ await writeJsonAtomic(filePath, board);
68
+ await writeJsonAtomic(path.join(root, 'active-board.json'), { boardId, updatedAt: now });
69
+ return { ok: true, boardId, revision: board.revision, status: board.status, path: path.relative(projectRoot, filePath), board };
70
+ }
71
+
72
+ export async function getProductionBoard({ projectRoot, boardId } = {}) {
73
+ const root = await ensureProjectDirectory(projectRoot, '.agentsam/primetech/boards');
74
+ const board = await readBoardFile(boardPath(root, boardId));
75
+ return { ok: true, boardId, revision: board.revision, status: board.status, board };
76
+ }
77
+
78
+ export async function listProductionBoards({ projectRoot } = {}) {
79
+ const root = await ensureProjectDirectory(projectRoot, '.agentsam/primetech/boards');
80
+ const names = await fs.readdir(root);
81
+ const boards = [];
82
+ for (const name of names.filter(name => /^ptb_[a-f0-9]{24}\.json$/.test(name))) {
83
+ try {
84
+ const board = await readBoardFile(path.join(root, name));
85
+ boards.push({ boardId: board.id, title: board.project.title, status: board.status, revision: board.revision, generationCount: board.generations.length, updatedAt: board.updatedAt });
86
+ } catch { /* corrupt records are not silently presented as valid boards */ }
87
+ }
88
+ boards.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
89
+ return { ok: true, count: boards.length, boards };
90
+ }
91
+
92
+ export async function beginGeneration({ projectRoot, boardId, generationId = null, idempotencyKey = null, kind, brief, prompt = '', sourceRefs = [], expectedRevision = null } = {}) {
93
+ if (typeof kind !== 'string' || !/^[a-z][a-z0-9_.-]{1,79}$/.test(kind)) throw new Error('production_generation_kind_invalid');
94
+ if (typeof brief !== 'string' || !brief.trim() || brief.length > 8000) throw new Error('production_generation_brief_required');
95
+ if (typeof prompt !== 'string' || prompt.length > 12000) throw new Error('production_generation_prompt_invalid');
96
+ if (!Array.isArray(sourceRefs) || sourceRefs.some(ref => typeof ref !== 'string' || ref.length > 1024)) throw new Error('production_generation_source_refs_invalid');
97
+ const root = await ensureProjectDirectory(projectRoot, '.agentsam/primetech/boards');
98
+ const filePath = boardPath(root, boardId);
99
+ return withBoardLock(filePath, async () => {
100
+ const board = await readBoardFile(filePath);
101
+ if (expectedRevision !== null && expectedRevision !== board.revision) throw new Error(`production_board_revision_conflict:${board.revision}`);
102
+ if (idempotencyKey) {
103
+ const prior = board.generations.find(item => item.idempotencyKey === idempotencyKey);
104
+ if (prior) return { ok: true, boardId, revision: board.revision, generationId: prior.id, status: prior.status, idempotentReplay: true, generation: prior };
105
+ }
106
+ const now = new Date().toISOString();
107
+ const record = {
108
+ id: generationId || id('gen'),
109
+ kind,
110
+ status: 'running',
111
+ brief: brief.trim(),
112
+ prompt,
113
+ sourceRefs,
114
+ idempotencyKey,
115
+ attempt: 1,
116
+ artifacts: [],
117
+ qualityChecks: [],
118
+ events: [{ type: 'generation.started', at: now }],
119
+ startedAt: now,
120
+ updatedAt: now,
121
+ };
122
+ if (board.generations.some(item => item.id === record.id)) throw new Error('production_generation_id_conflict');
123
+ board.generations.push(record);
124
+ await saveBoard(filePath, board, board.revision);
125
+ return { ok: true, boardId, revision: board.revision, generationId: record.id, status: record.status, generation: record };
126
+ });
127
+ }
128
+
129
+ export async function completeGeneration({ projectRoot, boardId, generationId, artifacts, qualityChecks = [], receipt = {}, expectedRevision = null } = {}) {
130
+ if (!Array.isArray(artifacts) || !artifacts.length || artifacts.some(item => !item || typeof item.ref !== 'string' || !item.ref.trim())) throw new Error('production_generation_artifacts_required');
131
+ if (!Array.isArray(qualityChecks) || !qualityChecks.length || qualityChecks.some(item => !item || typeof item.name !== 'string' || !['pass', 'fail', 'warn'].includes(item.status))) throw new Error('production_generation_quality_checks_required');
132
+ const root = await ensureProjectDirectory(projectRoot, '.agentsam/primetech/boards');
133
+ const filePath = boardPath(root, boardId);
134
+ return withBoardLock(filePath, async () => {
135
+ const board = await readBoardFile(filePath);
136
+ if (expectedRevision !== null && expectedRevision !== board.revision) throw new Error(`production_board_revision_conflict:${board.revision}`);
137
+ const generation = board.generations.find(item => item.id === generationId);
138
+ if (!generation) throw new Error('production_generation_not_found');
139
+ if (generation.status !== 'running' && generation.status !== 'needs_review') throw new Error(`production_generation_not_running:${generation.status}`);
140
+ const now = new Date().toISOString();
141
+ const passed = qualityChecks.every(item => item.status === 'pass');
142
+ generation.status = passed ? 'completed' : 'needs_review';
143
+ generation.artifacts = artifacts;
144
+ generation.qualityChecks = qualityChecks;
145
+ generation.receipt = receipt && typeof receipt === 'object' ? receipt : {};
146
+ generation.completedAt = passed ? now : null;
147
+ generation.updatedAt = now;
148
+ generation.events.push({ type: passed ? 'generation.completed' : 'generation.quality_review_required', at: now, failedChecks: qualityChecks.filter(item => item.status === 'fail').map(item => item.name) });
149
+ await saveBoard(filePath, board, board.revision);
150
+ return { ok: true, boardId, revision: board.revision, generationId, status: generation.status, qualityPassed: passed, generation };
151
+ });
152
+ }
153
+
154
+ export async function failGeneration({ projectRoot, boardId, generationId, error, retryable = true, expectedRevision = null } = {}) {
155
+ if (!error || typeof error !== 'object' || typeof error.code !== 'string') throw new Error('production_generation_error_code_required');
156
+ const root = await ensureProjectDirectory(projectRoot, '.agentsam/primetech/boards');
157
+ const filePath = boardPath(root, boardId);
158
+ return withBoardLock(filePath, async () => {
159
+ const board = await readBoardFile(filePath);
160
+ if (expectedRevision !== null && expectedRevision !== board.revision) throw new Error(`production_board_revision_conflict:${board.revision}`);
161
+ const generation = board.generations.find(item => item.id === generationId);
162
+ if (!generation) throw new Error('production_generation_not_found');
163
+ if (generation.status !== 'running' && generation.status !== 'needs_review') throw new Error(`production_generation_not_running:${generation.status}`);
164
+ const now = new Date().toISOString();
165
+ generation.status = 'failed';
166
+ generation.error = { code: error.code, message: String(error.message || '').slice(0, 1000) };
167
+ generation.retryable = Boolean(retryable);
168
+ generation.updatedAt = now;
169
+ generation.events.push({ type: 'generation.failed', at: now, code: error.code, retryable: Boolean(retryable) });
170
+ await saveBoard(filePath, board, board.revision);
171
+ return { ok: true, boardId, revision: board.revision, generationId, status: generation.status, retryable: generation.retryable, generation };
172
+ });
173
+ }
174
+
175
+ export async function resumeProductionBoard({ projectRoot, boardId } = {}) {
176
+ const result = await getProductionBoard({ projectRoot, boardId });
177
+ const resumable = result.board.generations.filter(item => ['running', 'failed', 'needs_review'].includes(item.status));
178
+ return { ok: true, boardId, revision: result.revision, status: result.status, resumableCount: resumable.length, resumable };
179
+ }
180
+
181
+ export const productionBoardContract = Object.freeze({ schema: BOARD_SCHEMA, generationStatuses: [...GENERATION_STATUSES] });
@@ -0,0 +1,48 @@
1
+ /** TypeScript declarations for the packaged PrimeTech skills. */
2
+ export interface PrimeTechSkillManifest {
3
+ schema: 'agentsam.skill.v1';
4
+ package: '@inneranimalmedia/primetech-procedures';
5
+ id: string;
6
+ name: string;
7
+ description: string;
8
+ icon?: string;
9
+ slash: { suggested: string };
10
+ instructions: { source: 'local_file'; ref: 'SKILL.md' };
11
+ execution: { mode: 'turn'; tools: string[]; operations: string[]; capabilities: string[] };
12
+ provenance: { source: string; status: string; notice?: string };
13
+ metadata?: Record<string, unknown>;
14
+ }
15
+ export interface PrimeTechSkill {
16
+ directory: string;
17
+ manifest: PrimeTechSkillManifest;
18
+ markdown: string;
19
+ path: string;
20
+ }
21
+ export interface PrimeTechSkillValidationEntry {
22
+ id: string;
23
+ name: string;
24
+ slash: string | null;
25
+ errors: string[];
26
+ valid: boolean;
27
+ }
28
+ export interface PrimeTechSkillPackageValidation {
29
+ schema: 'agentsam.primetech.skill-catalog-validation.v1';
30
+ valid: boolean;
31
+ count: number;
32
+ validCount: number;
33
+ invalidCount: number;
34
+ errors: string[];
35
+ skills: PrimeTechSkillValidationEntry[];
36
+ }
37
+ export interface LoadPrimeTechSkillCatalogOptions { root?: string; }
38
+ export interface ValidatePrimeTechSkillPackageOptions {
39
+ root?: string;
40
+ knownTools?: string[] | null;
41
+ knownOperations?: string[] | null;
42
+ knownCapabilities?: string[] | null;
43
+ expectedCount?: number | null;
44
+ }
45
+ export function loadPrimeTechSkillCatalog(options?: LoadPrimeTechSkillCatalogOptions): Promise<PrimeTechSkill[]>;
46
+ export function validatePrimeTechSkillPackage(options?: ValidatePrimeTechSkillPackageOptions): Promise<PrimeTechSkillPackageValidation>;
47
+ export function getPrimeTechSkill(options: { root?: string; id: string }): Promise<PrimeTechSkill | null>;
48
+ export const PRIMETECH_SKILL_CONTRACT_SECTIONS: readonly string[];
package/src/skills.js ADDED
@@ -0,0 +1,101 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ const DEFAULT_SKILL_ROOT = fileURLToPath(new URL('../skills/', import.meta.url));
6
+
7
+ export const PRIMETECH_SKILL_CONTRACT_SECTIONS = Object.freeze([
8
+ 'Trigger conditions', 'Inputs', 'Prerequisites', 'Workflow', 'Artifact contract',
9
+ 'Quality gates', 'Persistence', 'Iteration', 'Handoff', 'Failure handling',
10
+ ]);
11
+
12
+ function parseFrontmatter(markdown) {
13
+ const match = String(markdown).match(/^---\s*\n([\s\S]*?)\n---\s*\n/);
14
+ if (!match) return { valid: false, name: null, description: null };
15
+ const values = {};
16
+ for (const line of match[1].split(/\r?\n/)) {
17
+ const row = line.match(/^([a-zA-Z0-9_-]+):\s*(.*)$/);
18
+ if (row) values[row[1]] = row[2].trim().replace(/^['"]|['"]$/g, '');
19
+ }
20
+ return { valid: true, name: values.name || null, description: values.description || null };
21
+ }
22
+
23
+ function validateSkillManifest(manifest, markdown, dirName, known = {}) {
24
+ const errors = [];
25
+ if (!manifest || manifest.schema !== 'agentsam.skill.v1') errors.push('manifest.schema must be agentsam.skill.v1');
26
+ if (!/^[a-z0-9][a-z0-9-]{2,79}$/.test(manifest?.id || '')) errors.push('manifest.id is invalid');
27
+ if (manifest?.id !== dirName) errors.push('directory name must equal manifest.id');
28
+ if (typeof manifest?.name !== 'string' || !manifest.name.trim()) errors.push('manifest.name is required');
29
+ if (typeof manifest?.description !== 'string' || !manifest.description.trim()) errors.push('manifest.description is required');
30
+ if (!/^\/[a-z0-9][a-z0-9-]*$/.test(manifest?.slash?.suggested || '')) errors.push('manifest.slash.suggested is invalid');
31
+ if (manifest?.instructions?.source !== 'local_file' || manifest?.instructions?.ref !== 'SKILL.md') errors.push('instructions must resolve to local SKILL.md');
32
+ if (manifest?.execution?.mode !== 'turn') errors.push('execution.mode must be turn');
33
+ for (const key of ['tools', 'operations', 'capabilities']) {
34
+ const values = manifest?.execution?.[key];
35
+ if (!Array.isArray(values) || values.some(value => typeof value !== 'string' || !value.trim())) errors.push(`execution.${key} must be an array of non-empty strings`);
36
+ else if (new Set(values).size !== values.length) errors.push(`execution.${key} contains duplicates`);
37
+ }
38
+ const frontmatter = parseFrontmatter(markdown);
39
+ if (!frontmatter.valid || !frontmatter.name || !frontmatter.description) errors.push('SKILL.md frontmatter requires name and description');
40
+ if (frontmatter.name && frontmatter.name !== manifest.name) errors.push('frontmatter name must match manifest name');
41
+ if (frontmatter.description && frontmatter.description !== manifest.description) errors.push('frontmatter description must match manifest description');
42
+ for (const section of PRIMETECH_SKILL_CONTRACT_SECTIONS) {
43
+ const pattern = new RegExp(`^#{2,3}\\s+(?:\\d+\\.\\s*)?${section.replace(/[.*+?^${}()|[\\]\\]/g, '\\$&')}\\s*$`, 'im');
44
+ if (!pattern.test(markdown)) errors.push(`missing Universal Skill Contract section: ${section}`);
45
+ }
46
+ for (const [key, available] of Object.entries(known)) {
47
+ if (!Array.isArray(available)) continue;
48
+ const refs = manifest?.execution?.[key] || [];
49
+ for (const ref of refs) if (!available.includes(ref)) errors.push(`unknown execution.${key} reference: ${ref}`);
50
+ }
51
+ return { id: manifest?.id || dirName, name: manifest?.name || dirName, slash: manifest?.slash?.suggested || null, errors, valid: errors.length === 0 };
52
+ }
53
+
54
+ export async function loadPrimeTechSkillCatalog({ root = DEFAULT_SKILL_ROOT } = {}) {
55
+ const entries = await fs.readdir(root, { withFileTypes: true });
56
+ const skills = [];
57
+ for (const entry of entries.filter(item => item.isDirectory()).sort((a, b) => a.name.localeCompare(b.name))) {
58
+ const dir = path.join(root, entry.name);
59
+ const [manifestText, markdown] = await Promise.all([
60
+ fs.readFile(path.join(dir, 'agentsam.skill.json'), 'utf8'),
61
+ fs.readFile(path.join(dir, 'SKILL.md'), 'utf8'),
62
+ ]);
63
+ skills.push({ directory: entry.name, manifest: JSON.parse(manifestText), markdown, path: dir });
64
+ }
65
+ return skills;
66
+ }
67
+
68
+ export async function validatePrimeTechSkillPackage({ root, knownTools = null, knownOperations = null, knownCapabilities = null, expectedCount = null } = {}) {
69
+ const skills = await loadPrimeTechSkillCatalog({ root });
70
+ const known = {};
71
+ if (knownTools) known.tools = knownTools;
72
+ if (knownOperations) known.operations = knownOperations;
73
+ if (knownCapabilities) known.capabilities = knownCapabilities;
74
+ const seenIds = new Set();
75
+ const seenSlashes = new Set();
76
+ const results = skills.map(skill => {
77
+ const result = validateSkillManifest(skill.manifest, skill.markdown, skill.directory, known);
78
+ if (seenIds.has(result.id)) result.errors.push('duplicate skill id');
79
+ if (seenSlashes.has(result.slash)) result.errors.push('duplicate slash trigger');
80
+ seenIds.add(result.id);
81
+ seenSlashes.add(result.slash);
82
+ result.valid = result.errors.length === 0;
83
+ return result;
84
+ });
85
+ const errors = [];
86
+ if (expectedCount !== null && skills.length !== expectedCount) errors.push(`expected ${expectedCount} skills; found ${skills.length}`);
87
+ return {
88
+ schema: 'agentsam.primetech.skill-catalog-validation.v1',
89
+ valid: errors.length === 0 && results.every(result => result.valid),
90
+ count: skills.length,
91
+ validCount: results.filter(result => result.valid).length,
92
+ invalidCount: results.filter(result => !result.valid).length,
93
+ errors,
94
+ skills: results,
95
+ };
96
+ }
97
+
98
+ export async function getPrimeTechSkill({ root, id }) {
99
+ const skills = await loadPrimeTechSkillCatalog({ root });
100
+ return skills.find(skill => skill.manifest.id === id) || null;
101
+ }