contextos-agents 2.0.0-beta.3 → 2.1.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 (57) hide show
  1. package/.agents/AGENTS.md +53 -33
  2. package/.agents/adapters/aider/export.js +41 -14
  3. package/.agents/adapters/claude/export.js +1 -1
  4. package/.agents/adapters/copilot/export.js +1 -1
  5. package/.agents/adapters/cursor/export.js +1 -1
  6. package/.agents/adapters/drift-detector.js +80 -7
  7. package/.agents/adapters/gemini/export.js +1 -1
  8. package/.agents/adapters/pure-compiler.js +10 -0
  9. package/.agents/adapters/shared.js +13 -4
  10. package/.agents/adapters/zed/export.js +1 -1
  11. package/.agents/compiled/registry.v2.json +29 -25
  12. package/.agents/compiled/registry.v2.sha256 +1 -1
  13. package/.agents/core/skills/context-os/SKILL.md +34 -37
  14. package/.agents/core/skills/engineering-workflow/SKILL.md +24 -24
  15. package/.agents/core/skills/gemini-precision/EXAMPLES.md +72 -0
  16. package/.agents/core/skills/gemini-precision/SKILL.md +2 -1
  17. package/.agents/core/skills/gemini-precision/TROUBLESHOOTING.md +25 -0
  18. package/.agents/core/skills/gemini-precision/skill.yaml +2 -0
  19. package/.agents/core/skills/gstack-roles/SKILL.md +7 -6
  20. package/.agents/core/skills/security/SKILL.md +44 -16
  21. package/.agents/core/skills/security/skill.yaml +0 -1
  22. package/.agents/ctx.js +16 -10
  23. package/.agents/doctor.js +7 -20
  24. package/.agents/generated/claude/skills/context-os/SKILL.md +34 -37
  25. package/.agents/generated/claude/skills/engineering-workflow/SKILL.md +24 -24
  26. package/.agents/generated/claude/skills/gemini-precision/SKILL.md +102 -1
  27. package/.agents/generated/claude/skills/gstack-roles/SKILL.md +7 -6
  28. package/.agents/generated/claude/skills/security/SKILL.md +44 -16
  29. package/.agents/generated/gemini/skills/context-os/SKILL.md +34 -37
  30. package/.agents/generated/gemini/skills/engineering-workflow/SKILL.md +24 -24
  31. package/.agents/generated/gemini/skills/gemini-precision/SKILL.md +105 -1
  32. package/.agents/generated/gemini/skills/gstack-roles/SKILL.md +7 -6
  33. package/.agents/generated/gemini/skills/security/SKILL.md +44 -125
  34. package/.agents/plugins.js +5 -4
  35. package/.agents/resolver/canonical-resolver.js +7 -7
  36. package/.agents/validate.js +69 -1
  37. package/LICENSE +201 -21
  38. package/NOTICE +4 -0
  39. package/README.md +87 -34
  40. package/bin/commands/hook.js +129 -0
  41. package/bin/commands/scan.js +70 -0
  42. package/bin/commands/update.js +7 -8
  43. package/bin/commands.js +39 -1
  44. package/bin/index.js +144 -33
  45. package/bin/lib/gate.js +171 -0
  46. package/bin/lib/git-snapshot.js +187 -0
  47. package/bin/lib/scan.js +380 -0
  48. package/package.json +10 -12
  49. package/.agents/core/skills/security/security.md +0 -106
  50. package/benchmarks/v2/analysis/statistics.js +0 -140
  51. package/benchmarks/v2/analysis/stats.js +0 -69
  52. package/benchmarks/v2/arms/arm-definitions.js +0 -79
  53. package/benchmarks/v2/dataset.schema.json +0 -34
  54. package/benchmarks/v2/evaluators/index.js +0 -25
  55. package/benchmarks/v2/evaluators/verified-success.js +0 -116
  56. package/benchmarks/v2/harness/runner.js +0 -88
  57. package/benchmarks/v2/pilot-tasks.json +0 -392
package/bin/commands.js CHANGED
@@ -195,13 +195,28 @@ const COMMAND_REGISTRY = {
195
195
  requiresProject: true,
196
196
  options: [],
197
197
  },
198
+ gate: {
199
+ name: 'gate',
200
+ description: 'Run quality gate validation and drift checks without disk mutation',
201
+ usage: 'contextos gate [--project <dir>] [--target <adapters>] [--profile <name>] [--json]',
202
+ requiresProject: false,
203
+ options: [
204
+ { flag: '--project <dir>', desc: 'Target project directory (default: cwd)' },
205
+ { flag: '--target <adapters>', desc: 'Adapters to verify (gemini, claude, cursor, copilot, aider, zed, all)' },
206
+ { flag: '--profile <name>', desc: 'Profile override for verification' },
207
+ { flag: '--json', desc: 'Output gate report in versioned JSON format' },
208
+ ],
209
+ },
198
210
  export: {
199
211
  name: 'export',
200
212
  description: 'Compile skills for target agent (gemini, claude, cursor, copilot, aider, zed, all)',
201
- usage: 'contextos export <target> [--profile <name>]',
213
+ usage: 'contextos export <target> [--check] [--project <dir>] [--profile <name>] [--json]',
202
214
  requiresProject: true,
203
215
  options: [
216
+ { flag: '--check', desc: 'Verify synchronization without modifying disk' },
217
+ { flag: '--project <dir>', desc: 'Target project directory (default: cwd)' },
204
218
  { flag: '--profile <name>', desc: 'Apply profile for this export run' },
219
+ { flag: '--json', desc: 'Output in JSON format' },
205
220
  ],
206
221
  },
207
222
  profile: {
@@ -293,6 +308,29 @@ const COMMAND_REGISTRY = {
293
308
  { flag: '--continue [txId]', desc: 'Attempt to resume and complete prepared transaction' },
294
309
  ],
295
310
  },
311
+ scan: {
312
+ name: 'scan',
313
+ description: 'Scan Git staged index for secrets, lazy stubs, and write-scope containment',
314
+ usage: 'contextos scan [--staged] [--secrets] [--placeholders] [--scope <file>] [--enforce] [--json]',
315
+ requiresProject: false,
316
+ options: [
317
+ { flag: '--staged', desc: 'Scan staged changes in Git index (default)' },
318
+ { flag: '--placeholders', desc: 'Detect unfinished lazy placeholder stubs in newly added code' },
319
+ { flag: '--scope <file>', desc: 'Verify staged files stay within declared task scope JSON' },
320
+ { flag: '--enforce', desc: 'Fail with exit code 1 if violations are detected' },
321
+ { flag: '--json', desc: 'Output scan results in versioned JSON format' },
322
+ ],
323
+ },
324
+ hook: {
325
+ name: 'hook',
326
+ description: 'Manage safe pre-commit Git governance hooks',
327
+ usage: 'contextos hook <install|uninstall>',
328
+ requiresProject: false,
329
+ options: [
330
+ { flag: 'install', desc: 'Install or update isolated pre-commit hook' },
331
+ { flag: 'uninstall', desc: 'Remove ContextOS hook block while preserving custom hooks' },
332
+ ],
333
+ },
296
334
  };
297
335
 
298
336
  /**
package/bin/index.js CHANGED
@@ -32,6 +32,15 @@ const flags = {
32
32
  const i = args.indexOf('--add-skill');
33
33
  return i !== -1 ? args[i + 1] : null;
34
34
  })(),
35
+ project: (() => {
36
+ const i = args.indexOf('--project');
37
+ return i !== -1 && args[i + 1] && !args[i + 1].startsWith('-') ? path.resolve(args[i + 1]) : process.cwd();
38
+ })(),
39
+ target: (() => {
40
+ const i = args.indexOf('--target');
41
+ return i !== -1 && args[i + 1] && !args[i + 1].startsWith('-') ? args[i + 1] : null;
42
+ })(),
43
+ githubAnnotations: args.includes('--github-annotations'),
35
44
  };
36
45
 
37
46
  // ── Help / Version ────────────────────────────────────────────────────────────
@@ -64,12 +73,16 @@ Options:
64
73
  --minimal Install only 7 core skills (lightweight footprint)
65
74
  --profile <name> Install a specific profile (mvp, startup, enterprise, frontend, backend)
66
75
  --auto Auto-detect tech stack and apply recommended profile
76
+ --project <path> Specify target project root directory (default: current directory)
77
+ --target <adapters> Target adapter(s) to verify or export (default: all)
78
+ --github-annotations Emit GitHub Actions workflow commands and step summary
67
79
  --with-mcp, --mcp [DEPRECATED] Use the separate @contextos/mcp package instead
68
80
  --skip-compile Skip running ctx.js export after installation
69
81
  --add-skill <ref> Install a community plugin skill after setup
70
82
 
71
83
  Commands:
72
84
  init Install and configure .agents/ in target project
85
+ gate Run deterministic quality gate against adapter drift
73
86
  status Display project configuration, active profile, and lockfile status
74
87
  update Safely update skills without overwriting custom changes
75
88
  uninstall Safely uninstall ContextOS files (preserves user custom skills)
@@ -84,6 +97,10 @@ Commands:
84
97
  watch Start continuous file watcher and auto-sync daemon
85
98
  detect Analyze project and display detected tech stack & IDE
86
99
  install-skill Interactive skill installer (or pass <ref> / --from-repo)
100
+ scan Scan Git staged changes for secrets, placeholders, and scope
101
+ hook <cmd> Manage isolated pre-commit Git governance hooks (install, uninstall)
102
+ recover List or recover from interrupted filesystem transactions
103
+ explain [rule] Inspect rule catalog, enforcement levels, and checkers
87
104
  setup-mcp [DEPRECATED] Add MCP execution server to an existing .agents/ project
88
105
 
89
106
  Profiles:
@@ -250,20 +267,138 @@ if (mainCommand === 'recover') {
250
267
  process.exit(0);
251
268
  }
252
269
 
253
- // Proxy commands to .agents/ctx.js when executed in a ContextOS project
270
+ // Gate command (deterministic quality gate verification)
271
+ if (mainCommand === 'gate') {
272
+ const { runGate, emitGitHubAnnotations, writeGitHubSummary } = require('./lib/gate.js');
273
+ const target = flags.target || (args[1] && !args[1].startsWith('-') ? args[1] : 'all');
274
+ const result = runGate(flags.project, {
275
+ target,
276
+ profile: flags.profile,
277
+ json: flags.json,
278
+ });
279
+
280
+ if (process.env.GITHUB_ACTIONS === 'true' || flags.githubAnnotations) {
281
+ emitGitHubAnnotations(result);
282
+ writeGitHubSummary(result);
283
+ }
284
+
285
+ if (flags.json) {
286
+ console.log(JSON.stringify(result, null, 2));
287
+ } else {
288
+ console.log(`\nContextOS Quality Gate (${result.schemaVersion})\n`);
289
+ console.log(` Project: ${result.projectRoot}`);
290
+ console.log(` Status : ${result.status.toUpperCase()} (code ${result.code})`);
291
+ console.log(` Message: ${result.message}\n`);
292
+ if (result.drift && result.drift.hasDrift) {
293
+ console.log(`! Drift detected (${result.drift.totalFindings} findings):`);
294
+ for (const [state, items] of Object.entries(result.drift.findings)) {
295
+ if (items.length > 0) {
296
+ console.log(` [${state}] (${items.length}):`);
297
+ for (const item of items) {
298
+ console.log(` • ${item.path || item.reason || JSON.stringify(item)}`);
299
+ }
300
+ }
301
+ }
302
+ if (result.drift.collisions && result.drift.collisions.length > 0) {
303
+ console.log(`\n [PATH_COLLISIONS] (${result.drift.collisions.length}):`);
304
+ for (const c of result.drift.collisions) {
305
+ console.log(` • ${c.path} (between ${c.firstAdapter} and ${c.secondAdapter})`);
306
+ }
307
+ }
308
+ }
309
+ }
310
+ process.exit(result.code);
311
+ }
312
+
313
+ // Export check mode (in-process verification without spawning untrusted project scripts)
314
+ if (mainCommand === 'export' && args.includes('--check')) {
315
+ const { detectDrift } = require('../.agents/adapters/drift-detector.js');
316
+ const rawTarget = flags.target || (args[1] && !args[1].startsWith('-') ? args[1] : 'all');
317
+ const drift = detectDrift(flags.project, rawTarget, { profile: flags.profile });
318
+
319
+ if (process.env.GITHUB_ACTIONS === 'true' || flags.githubAnnotations) {
320
+ const { emitGitHubAnnotations, writeGitHubSummary } = require('./lib/gate.js');
321
+ const gateFormat = {
322
+ ok: !drift.hasDrift && !drift.hasError,
323
+ code: drift.code !== undefined ? drift.code : (drift.hasDrift ? 1 : 0),
324
+ status: drift.status || (drift.hasError ? 'error' : (drift.hasDrift ? 'drift' : 'pass')),
325
+ projectRoot: flags.project,
326
+ target: rawTarget,
327
+ profile: flags.profile || 'default',
328
+ drift,
329
+ message: drift.hasDrift ? 'Adapter drift detected' : 'Artifacts synchronized',
330
+ };
331
+ emitGitHubAnnotations(gateFormat);
332
+ writeGitHubSummary(gateFormat);
333
+ }
334
+
335
+ if (flags.json) {
336
+ console.log(JSON.stringify(drift, null, 2));
337
+ } else {
338
+ console.log('\nContextOS - Adapter Output Drift Check\n');
339
+ console.log(` Project: ${flags.project}`);
340
+ if (!drift.hasDrift && !drift.hasError) {
341
+ console.log(`✓ No adapter drift detected. All ${drift.projectedCount} output artifacts are synchronized.`);
342
+ } else {
343
+ console.log(`! Drift detected (${drift.totalFindings} finding(s)):\n`);
344
+ for (const [state, items] of Object.entries(drift.findings)) {
345
+ if (items.length > 0) {
346
+ console.log(` [${state}] (${items.length}):`);
347
+ for (const item of items) {
348
+ console.log(` • ${item.path || item.reason || JSON.stringify(item)}`);
349
+ }
350
+ }
351
+ }
352
+ if (drift.collisions && drift.collisions.length > 0) {
353
+ console.log(`\n [PATH_COLLISIONS] (${drift.collisions.length}):`);
354
+ for (const c of drift.collisions) {
355
+ console.log(` • ${c.path} (between ${c.firstAdapter} and ${c.secondAdapter})`);
356
+ }
357
+ }
358
+ console.log('\nRun: contextos export all to synchronize outputs with source skills.\n');
359
+ }
360
+ }
361
+ process.exit(drift.code !== undefined ? drift.code : (drift.hasDrift ? 1 : 0));
362
+ }
363
+
364
+ // Scan command (Git staged index security and placeholder scanner)
365
+ if (mainCommand === 'scan') {
366
+ const scanModule = require('./commands/scan.js');
367
+ scanModule(args, flags);
368
+ process.exit(0);
369
+ }
370
+
371
+ // Hook command (safe Git hook lifecycle management)
372
+ if (mainCommand === 'hook') {
373
+ const { hookCommand } = require('./commands/hook.js');
374
+ hookCommand(args, flags);
375
+ process.exit(0);
376
+ }
377
+
378
+ // Proxy commands to trusted package .agents/ctx.js targeting flags.project
254
379
  const PROXY_COMMANDS = [
255
380
  'profile', 'export', 'validate', 'resolve', 'skill', 'index',
256
381
  'clean-worktrees', 'stats', 'watch', 'compile', 'explain',
257
382
  'thread'
258
383
  ];
259
384
 
260
- const ctxPath = path.join(process.cwd(), '.agents', 'ctx.js');
261
- const hasLocalCtx = fs.existsSync(ctxPath);
385
+ const packageCtxPath = path.join(__dirname, '..', '.agents', 'ctx.js');
262
386
 
263
- if (mainCommand && PROXY_COMMANDS.includes(mainCommand) && hasLocalCtx) {
387
+ if (mainCommand && PROXY_COMMANDS.includes(mainCommand)) {
264
388
  const { execFileSync } = require('child_process');
389
+ const filteredArgs = [];
390
+ for (let i = 0; i < args.length; i++) {
391
+ if (args[i] === '--project') {
392
+ i++; // skip project path
393
+ continue;
394
+ }
395
+ filteredArgs.push(args[i]);
396
+ }
265
397
  try {
266
- execFileSync(process.execPath, [ctxPath, ...args], { stdio: 'inherit' });
398
+ execFileSync(process.execPath, [packageCtxPath, ...filteredArgs], {
399
+ cwd: flags.project,
400
+ stdio: 'inherit',
401
+ });
267
402
  } catch (e) {
268
403
  process.exit(e.status || 1);
269
404
  }
@@ -300,34 +435,7 @@ if (mainCommand === 'watch') {
300
435
  watchModule.runWatch(process.cwd());
301
436
  }
302
437
 
303
- const PROJECT_ONLY_COMMANDS = ['profile', 'export', 'validate', 'resolve', 'skill', 'index', 'clean-worktrees', 'compile', 'explain'];
304
- if (mainCommand && PROJECT_ONLY_COMMANDS.includes(mainCommand) && !hasLocalCtx) {
305
- console.error('[ERROR] .agents/ctx.js not found in current directory.');
306
- console.error(' Are you in a ContextOS project? Run `contextos` or `npx contextos-agents` first.');
307
- process.exit(1);
308
- }
309
-
310
- if (mainCommand === 'audit') {
311
- if (!hasLocalCtx) {
312
- console.error('[ERROR] .agents/ctx.js not found. Are you in a ContextOS project?');
313
- process.exit(1);
314
- }
315
- const { execFileSync } = require('child_process');
316
- try {
317
- execFileSync(process.execPath, [ctxPath, 'validate'], { stdio: 'inherit' });
318
- } catch (e) {
319
- process.exit(1);
320
- }
321
- process.exit(0);
322
- }
323
-
324
438
  if (mainCommand === 'install-skill') {
325
- const ctxPath = path.join(process.cwd(), '.agents', 'ctx.js');
326
- if (!fs.existsSync(ctxPath)) {
327
- console.error('[ERROR] .agents/ctx.js not found. Are you in a ContextOS project?');
328
- process.exit(1);
329
- }
330
-
331
439
  const fromRepo = (() => {
332
440
  const i = args.indexOf('--from-repo');
333
441
  return i !== -1 ? args[i + 1] : null;
@@ -338,7 +446,10 @@ if (mainCommand === 'install-skill') {
338
446
  if (ref) {
339
447
  const { execFileSync } = require('child_process');
340
448
  try {
341
- execFileSync(process.execPath, [ctxPath, 'skill', 'add', ref], { stdio: 'inherit' });
449
+ execFileSync(process.execPath, [packageCtxPath, 'skill', 'add', ref], {
450
+ cwd: flags.project,
451
+ stdio: 'inherit',
452
+ });
342
453
  } catch (e) {
343
454
  process.exit(1);
344
455
  }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * bin/lib/gate.js
3
+ * ContextOS - Quality Gate Verification Engine
4
+ *
5
+ * Implements deterministic verification paths without executing untrusted
6
+ * user project scripts. Operates in-process using trusted package modules.
7
+ */
8
+
9
+ 'use strict';
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const { detectDrift } = require('../../.agents/adapters/drift-detector.js');
14
+ const pureCompiler = require('../../.agents/adapters/pure-compiler.js');
15
+
16
+ /**
17
+ * Runs the quality gate against a target project root.
18
+ *
19
+ * @param {string} [projectRoot=process.cwd()] - Target project directory
20
+ * @param {object} [options]
21
+ * @param {string|string[]} [options.target='all'] - Adapters to verify
22
+ * @param {string} [options.profile=null] - Profile name or override
23
+ * @param {boolean} [options.json=false] - Format as machine-readable JSON
24
+ * @returns {{ ok: boolean, code: number, status: string, drift: object, message: string }}
25
+ */
26
+ function runGate(projectRoot = process.cwd(), options = {}) {
27
+ const absRoot = path.resolve(projectRoot);
28
+ const target = options.target || 'all';
29
+ const profile = options.profile || null;
30
+
31
+ // 1. Run Drift Detection via trusted in-package drift-detector
32
+ const drift = detectDrift(absRoot, target, { profile });
33
+
34
+ let status = 'pass';
35
+ let code = 0;
36
+ let message = 'All adapter outputs are synchronized with source skills.';
37
+
38
+ if (drift.hasError) {
39
+ status = 'error';
40
+ code = drift.code || 2;
41
+ message = drift.error || 'Configuration or execution error occurred during verification.';
42
+ } else if (drift.hasDrift) {
43
+ status = 'drift';
44
+ code = drift.code || 1;
45
+ message = `Adapter drift detected across ${drift.totalFindings} finding(s).`;
46
+ }
47
+
48
+ const result = {
49
+ schemaVersion: '2.0.0',
50
+ status,
51
+ code,
52
+ ok: code === 0,
53
+ projectRoot: absRoot,
54
+ target,
55
+ profile,
56
+ message,
57
+ drift,
58
+ };
59
+
60
+ return result;
61
+ }
62
+
63
+ /**
64
+ * Emits GitHub Actions workflow annotations for drift or errors.
65
+ *
66
+ * @param {object} result - Gate result
67
+ */
68
+ function emitGitHubAnnotations(result) {
69
+ if (!result || !result.drift) return;
70
+
71
+ const escapeActionData = (str) =>
72
+ String(str)
73
+ .replace(/%/g, '%25')
74
+ .replace(/\r/g, '%0D')
75
+ .replace(/\n/g, '%0A');
76
+
77
+ const normalizePath = (p) => (p ? String(p).replace(/\\/g, '/') : '');
78
+
79
+ const { findings, collisions } = result.drift;
80
+
81
+ if (findings) {
82
+ for (const item of findings.MISSING_OUTPUT || []) {
83
+ console.error(`::error file=${normalizePath(item.path)}::[MISSING_OUTPUT] ${escapeActionData(item.reason || 'Missing projected output file')}`);
84
+ }
85
+ for (const item of findings.MODIFIED_MANAGED_OUTPUT || []) {
86
+ console.error(`::error file=${normalizePath(item.path)}::[MODIFIED_OUTPUT] ${escapeActionData(item.reason || 'Managed output modified on disk')}`);
87
+ }
88
+ for (const item of findings.ORPHAN_MANAGED_OUTPUT || []) {
89
+ console.error(`::warning file=${normalizePath(item.path)}::[ORPHAN_OUTPUT] ${escapeActionData(item.reason || 'Orphan file recorded in lockfile')}`);
90
+ }
91
+ for (const item of findings.CORRUPT_LOCKFILE || []) {
92
+ console.error(`::error::[CORRUPT_LOCKFILE] ${escapeActionData(item.reason || 'Lockfile is corrupt')}`);
93
+ }
94
+ for (const item of findings.CONFIG_ERROR || []) {
95
+ console.error(`::error::[CONFIG_ERROR] ${escapeActionData(item.reason || 'Configuration error')}`);
96
+ }
97
+ for (const item of findings.EMPTY_PROJECTION || []) {
98
+ console.error(`::error::[EMPTY_PROJECTION] ${escapeActionData(item.reason || 'Projected artifact set is empty')}`);
99
+ }
100
+ }
101
+
102
+ for (const c of collisions || []) {
103
+ console.error(`::error file=${normalizePath(c.path)}::[PATH_COLLISION] Collision between adapter ${c.firstAdapter} and ${c.secondAdapter}`);
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Formats a markdown summary for GitHub Step Summary.
109
+ *
110
+ * @param {object} result - Gate result
111
+ * @returns {string} Markdown summary
112
+ */
113
+ function formatGitHubSummary(result) {
114
+ const icon = result.ok ? '✅' : (result.status === 'drift' ? '⚠️' : '❌');
115
+ const lines = [
116
+ `# ${icon} ContextOS Quality Gate Report`,
117
+ '',
118
+ `**Status**: \`${result.status.toUpperCase()}\` (exit code: \`${result.code}\`) `,
119
+ `**Project Root**: \`${result.projectRoot}\` `,
120
+ `**Target Adapters**: \`${Array.isArray(result.target) ? result.target.join(', ') : result.target}\` `,
121
+ `**Active Profile**: \`${result.profile || 'default'}\` `,
122
+ `**Projected Artifacts**: \`${result.drift?.projectedCount || 0}\` `,
123
+ '',
124
+ `### Overview`,
125
+ result.message,
126
+ '',
127
+ ];
128
+
129
+ if (result.drift && result.drift.totalFindings > 0) {
130
+ lines.push(`### Findings (${result.drift.totalFindings})`);
131
+ lines.push('| State | Path | Detail |');
132
+ lines.push('| --- | --- | --- |');
133
+
134
+ for (const [state, items] of Object.entries(result.drift.findings)) {
135
+ for (const item of items) {
136
+ const itemPath = item.path ? `\`${item.path}\`` : '*(project)*';
137
+ const detail = (item.reason || item.diff || '').replace(/\|/g, '\\|');
138
+ lines.push(`| **${state}** | ${itemPath} | ${detail} |`);
139
+ }
140
+ }
141
+ lines.push('');
142
+ lines.push('> **Remediation**: Run `npx contextos-agents export all` and commit synchronized adapter artifacts.');
143
+ lines.push('');
144
+ }
145
+
146
+ return lines.join('\n');
147
+ }
148
+
149
+ /**
150
+ * Writes the markdown summary to GITHUB_STEP_SUMMARY if available.
151
+ *
152
+ * @param {object} result - Gate result
153
+ */
154
+ function writeGitHubSummary(result) {
155
+ const summaryFile = process.env.GITHUB_STEP_SUMMARY;
156
+ if (!summaryFile) return;
157
+
158
+ try {
159
+ const summaryMd = formatGitHubSummary(result);
160
+ fs.appendFileSync(summaryFile, summaryMd + '\n', 'utf8');
161
+ } catch {
162
+ // Best-effort write to step summary
163
+ }
164
+ }
165
+
166
+ module.exports = {
167
+ runGate,
168
+ emitGitHubAnnotations,
169
+ formatGitHubSummary,
170
+ writeGitHubSummary,
171
+ };
@@ -0,0 +1,187 @@
1
+ /**
2
+ * bin/lib/git-snapshot.js
3
+ * ContextOS Git Index Snapshot & Staged Blob Reader
4
+ *
5
+ * Inspects staged changes directly from the Git index without modifying
6
+ * the working directory. Safely handles NUL-delimited filenames, Unicode,
7
+ * binary files, and path spaces.
8
+ */
9
+
10
+ 'use strict';
11
+
12
+ const path = require('path');
13
+ const { execFileSync } = require('child_process');
14
+
15
+ /**
16
+ * Finds the top-level repository root via Git.
17
+ *
18
+ * @param {string} [cwd=process.cwd()] - Working directory
19
+ * @returns {string|null} Absolute repository root or null if not a Git repository
20
+ */
21
+ function findGitRoot(cwd = process.cwd()) {
22
+ try {
23
+ const root = execFileSync('git', ['rev-parse', '--show-toplevel'], {
24
+ cwd,
25
+ encoding: 'utf8',
26
+ stdio: ['pipe', 'pipe', 'pipe'],
27
+ });
28
+ return path.resolve(root.trim());
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Discovers the git hooks directory, respecting core.hooksPath if set.
36
+ *
37
+ * @param {string} [cwd=process.cwd()] - Working directory
38
+ * @returns {string|null} Absolute path to hooks directory or null
39
+ */
40
+ function findHooksDir(cwd = process.cwd()) {
41
+ try {
42
+ const gitDir = execFileSync('git', ['rev-parse', '--git-path', 'hooks'], {
43
+ cwd,
44
+ encoding: 'utf8',
45
+ stdio: ['pipe', 'pipe', 'pipe'],
46
+ }).trim();
47
+ return path.resolve(cwd, gitDir);
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Retrieves the list of staged files from the Git index.
55
+ * Uses NUL-delimited output (-z) to support spaces, Unicode, and escapes.
56
+ *
57
+ * @param {string} [cwd=process.cwd()] - Working directory
58
+ * @returns {Array<{ status: string, path: string, oldPath?: string }>} Staged entries
59
+ */
60
+ function getStagedFiles(cwd = process.cwd()) {
61
+ try {
62
+ const output = execFileSync(
63
+ 'git',
64
+ ['diff', '--cached', '-z', '--name-status'],
65
+ { cwd, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }
66
+ );
67
+
68
+ if (!output) return [];
69
+
70
+ const parts = output.split('\0');
71
+ const entries = [];
72
+
73
+ let i = 0;
74
+ while (i < parts.length) {
75
+ const statusRaw = parts[i];
76
+ if (!statusRaw) {
77
+ i++;
78
+ continue;
79
+ }
80
+
81
+ const status = statusRaw[0];
82
+ if (status === 'R' || status === 'C') {
83
+ // Rename or copy includes old path followed by new path
84
+ const oldPath = parts[i + 1];
85
+ const newPath = parts[i + 2];
86
+ if (newPath) {
87
+ entries.push({ status, path: newPath, oldPath });
88
+ }
89
+ i += 3;
90
+ } else {
91
+ const filePath = parts[i + 1];
92
+ if (filePath) {
93
+ entries.push({ status, path: filePath });
94
+ }
95
+ i += 2;
96
+ }
97
+ }
98
+
99
+ return entries;
100
+ } catch (err) {
101
+ throw new Error(`Failed to query staged files from Git: ${err.message}`);
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Reads the content of a file directly from the Git staged index.
107
+ *
108
+ * @param {string} relativePath - Path relative to repo root
109
+ * @param {string} [cwd=process.cwd()] - Working directory
110
+ * @returns {Buffer|null} Staged file buffer or null if deleted/missing
111
+ */
112
+ function getStagedBlob(relativePath, cwd = process.cwd()) {
113
+ try {
114
+ const posixPath = relativePath.replace(/\\/g, '/');
115
+ const buf = execFileSync('git', ['show', `:${posixPath}`], {
116
+ cwd,
117
+ stdio: ['pipe', 'pipe', 'pipe'],
118
+ maxBuffer: 10 * 1024 * 1024,
119
+ });
120
+ return buf;
121
+ } catch (err) {
122
+ // If file was deleted or unreadable in index, return null
123
+ return null;
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Extracts added lines from git diff --cached -U0 for each staged file.
129
+ * Returns only lines that were added (+), excluding diff headers and deleted lines (-).
130
+ *
131
+ * @param {string} [cwd=process.cwd()] - Working directory
132
+ * @returns {Map<string, Array<{ line: number, content: string }>>} Added lines by file
133
+ */
134
+ function getStagedAddedLines(cwd = process.cwd()) {
135
+ const addedLinesByFile = new Map();
136
+
137
+ try {
138
+ const diffOutput = execFileSync('git', ['diff', '--cached', '-U0'], {
139
+ cwd,
140
+ encoding: 'utf8',
141
+ stdio: ['pipe', 'pipe', 'pipe'],
142
+ maxBuffer: 10 * 1024 * 1024,
143
+ });
144
+
145
+ if (!diffOutput) return addedLinesByFile;
146
+
147
+ const lines = diffOutput.split(/\r?\n/);
148
+ let currentFile = null;
149
+ let currentLineNum = 0;
150
+
151
+ for (const line of lines) {
152
+ if (line.startsWith('+++ b/')) {
153
+ currentFile = line.slice(6).trim();
154
+ if (!addedLinesByFile.has(currentFile)) {
155
+ addedLinesByFile.set(currentFile, []);
156
+ }
157
+ } else if (line.startsWith('@@ ')) {
158
+ // Parse @@ -a,b +c,d @@ to get current target line number
159
+ const match = line.match(/\+([0-9]+)(?:,([0-9]+))?/);
160
+ if (match) {
161
+ currentLineNum = parseInt(match[1], 10);
162
+ }
163
+ } else if (line.startsWith('+') && !line.startsWith('+++')) {
164
+ if (currentFile) {
165
+ const content = line.slice(1);
166
+ addedLinesByFile.get(currentFile).push({
167
+ line: currentLineNum,
168
+ content,
169
+ });
170
+ }
171
+ currentLineNum++;
172
+ }
173
+ }
174
+
175
+ return addedLinesByFile;
176
+ } catch {
177
+ return addedLinesByFile;
178
+ }
179
+ }
180
+
181
+ module.exports = {
182
+ findGitRoot,
183
+ findHooksDir,
184
+ getStagedFiles,
185
+ getStagedBlob,
186
+ getStagedAddedLines,
187
+ };