@aiwg/cli 2026.11.0 → 2026.11.2

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 (168) hide show
  1. package/agentic/code/addons/aiwg-hooks/canonical/aiwg-prompt-discovery.yaml +9 -0
  2. package/agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs +136 -0
  3. package/agentic/code/providers/flue/README.md +2 -1
  4. package/agentic/code/providers/model-capabilities.v1.json +27 -23
  5. package/agentic/code/providers/model-catalog.v1.json +3 -3
  6. package/dist/src/artifacts/cli.js +13 -13
  7. package/dist/src/artifacts/discover-cli-help.js +25 -0
  8. package/dist/src/artifacts/discover-facets.js +2 -0
  9. package/dist/src/artifacts/discover-session-facets.js +15 -0
  10. package/dist/src/artifacts/fortemi-core-prebuilt-freshness.js +28 -0
  11. package/dist/src/artifacts/fortemi-core-query-adapter.js +4 -4
  12. package/dist/src/artifacts/fortemi-core-sync.js +3 -0
  13. package/dist/src/artifacts/framework-capabilities.js +11 -3
  14. package/dist/src/artifacts/framework-source-digest.js +1 -1
  15. package/dist/src/artifacts/index-builder.js +12 -13
  16. package/dist/src/artifacts/index-dependencies.js +72 -0
  17. package/dist/src/artifacts/query-engine-discover-output.js +13 -5
  18. package/dist/src/artifacts/query-engine-discover.js +103 -28
  19. package/dist/src/artifacts/query-engine-entries.js +107 -10
  20. package/dist/src/artifacts/query-engine-installation.js +27 -0
  21. package/dist/src/artifacts/query-engine-options.js +14 -1
  22. package/dist/src/artifacts/query-engine-rules.js +1 -2
  23. package/dist/src/artifacts/query-engine-scoring.js +38 -32
  24. package/dist/src/artifacts/query-engine-show-card.js +8 -2
  25. package/dist/src/artifacts/query-engine-show-load.js +1 -1
  26. package/dist/src/artifacts/query-engine-show.js +5 -3
  27. package/dist/src/artifacts/query-engine-templates.js +33 -0
  28. package/dist/src/artifacts/query-engine-verbose.js +25 -0
  29. package/dist/src/artifacts/relations-builder.js +49 -4
  30. package/dist/src/artifacts/relations.js +26 -10
  31. package/dist/src/artifacts/template-references.js +42 -0
  32. package/dist/src/artifacts/types.js +1 -1
  33. package/dist/src/cli/handlers/bundle-reconciliation.js +7 -3
  34. package/dist/src/cli/handlers/checkpoint-handoff.js +48 -0
  35. package/dist/src/cli/handlers/checkpoint-record.js +20 -0
  36. package/dist/src/cli/handlers/checkpoint.js +176 -0
  37. package/dist/src/cli/handlers/decision.js +1 -1
  38. package/dist/src/cli/handlers/doctor-args.js +3 -1
  39. package/dist/src/cli/handlers/doctor-help.js +2 -1
  40. package/dist/src/cli/handlers/help.js +1 -0
  41. package/dist/src/cli/handlers/index.js +4 -2
  42. package/dist/src/cli/handlers/models-resource-sample.js +7 -3
  43. package/dist/src/cli/handlers/ralph-launcher.js +1 -1
  44. package/dist/src/cli/handlers/refresh-bundles.js +2 -1
  45. package/dist/src/cli/handlers/refresh-managed-deployment.js +196 -0
  46. package/dist/src/cli/handlers/refresh.js +10 -2
  47. package/dist/src/cli/handlers/script-runner.js +2 -1
  48. package/dist/src/cli/handlers/steward-signing.js +44 -0
  49. package/dist/src/cli/handlers/steward.js +5 -0
  50. package/dist/src/cli/handlers/subcommands-discovery.js +8 -1
  51. package/dist/src/cli/handlers/use-provider-results.js +17 -0
  52. package/dist/src/cli/handlers/use.js +19 -18
  53. package/dist/src/cli/router.js +12 -2
  54. package/dist/src/cli/services/deployment-verification.js +11 -7
  55. package/dist/src/cli/user-scope-mirror.js +3 -1
  56. package/dist/src/config/aiwg-config.js +5 -1
  57. package/dist/src/config/cli.js +1 -0
  58. package/dist/src/config/delivery-validation.js +21 -0
  59. package/dist/src/config/host-resource-report.d.mts +1 -1
  60. package/dist/src/config/host-resource-report.mjs +23 -4
  61. package/dist/src/config/host-resource-runtime.d.mts +8 -0
  62. package/dist/src/config/host-resource-runtime.mjs +67 -24
  63. package/dist/src/config/index-graph-overrides.js +4 -0
  64. package/dist/src/config/worker-attribution.d.mts +7 -0
  65. package/dist/src/config/worker-attribution.mjs +44 -0
  66. package/dist/src/config/worker-write.js +4 -10
  67. package/dist/src/decision/ledger.js +15 -15
  68. package/dist/src/decision/offload.js +6 -7
  69. package/dist/src/delivery/git.js +62 -0
  70. package/dist/src/delivery/pr.js +151 -0
  71. package/dist/src/delivery/template-sections.js +56 -0
  72. package/dist/src/delivery/tracker.js +33 -0
  73. package/dist/src/discovery/interview.js +1 -1
  74. package/dist/src/extensions/claude-hooks-installer.js +62 -53
  75. package/dist/src/extensions/loader.js +2 -1
  76. package/dist/src/extensions/managed-hook-script-state.js +48 -0
  77. package/dist/src/extensions/muse-managed-hooks.js +49 -0
  78. package/dist/src/issues/cli.js +15 -3
  79. package/dist/src/issues/external-cli.js +79 -0
  80. package/dist/src/issues/live.js +26 -2
  81. package/dist/src/issues/local.js +5 -1
  82. package/dist/src/issues/tracker-policy.js +27 -0
  83. package/dist/src/mcp/json-document.d.mts +2 -0
  84. package/dist/src/mcp/tools/worker-invoke.mjs +2 -1
  85. package/dist/src/mcp/tools/worker-stdin-runtime.mjs +12 -0
  86. package/dist/src/models/conductor-data-policy.d.mts +3 -2
  87. package/dist/src/models/conductor-data-policy.mjs +94 -5
  88. package/dist/src/models/model-capabilities.v1.json +27 -23
  89. package/dist/src/models/model-catalog.v1.json +3 -3
  90. package/dist/src/models/provider-policy.js +8 -0
  91. package/dist/src/models/worker-health-readiness.js +20 -4
  92. package/dist/src/models/worker-health-snapshot.js +29 -0
  93. package/dist/src/models/worker-installation.d.mts +5 -1
  94. package/dist/src/models/worker-installation.mjs +11 -5
  95. package/dist/src/models/worker-plan.js +3 -3
  96. package/dist/src/models/worker-qualification-policy.js +54 -0
  97. package/dist/src/models/worker-selection-policy.js +2 -1
  98. package/dist/src/providers/deployment-lock.js +77 -0
  99. package/dist/src/providers/deployment-ownership.d.mts +12 -2
  100. package/dist/src/providers/deployment-ownership.mjs +115 -21
  101. package/dist/src/providers/deployment-preservation.d.mts +2 -1
  102. package/dist/src/providers/deployment-preservation.mjs +3 -0
  103. package/dist/src/providers/provider-definitions.js +4 -0
  104. package/dist/src/providers/skill-ownership.d.mts +1 -0
  105. package/dist/src/providers/transformation-receipt-integration.js +4 -2
  106. package/dist/src/providers/transformation-receipt.js +4 -2
  107. package/dist/src/serve/worker-invocation-preparation.js +3 -1
  108. package/dist/src/serve/worker-invocation.js +6 -2
  109. package/dist/src/skills/run.js +5 -0
  110. package/dist/src/smiths/context-pipeline/workspace-audit.js +34 -17
  111. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +12 -6
  112. package/dist/src/smiths/context-pipeline/workspace-doctor.js +44 -4
  113. package/dist/src/smiths/context-pipeline/workspace-document.js +5 -2
  114. package/dist/src/smiths/context-pipeline/workspace-migration.js +2 -1
  115. package/dist/src/smiths/hook-bridge/codex-translator.js +150 -92
  116. package/dist/src/smiths/hook-bridge/codex-trust.js +50 -0
  117. package/dist/src/smiths/hook-bridge/factory-hook-config.js +132 -0
  118. package/dist/src/smiths/hook-bridge/factory-translator.js +88 -33
  119. package/dist/src/smiths/hook-bridge/hermes-translator.js +3 -1
  120. package/dist/src/smiths/hook-bridge/index.js +3 -3
  121. package/dist/src/smiths/hook-bridge/loader.js +10 -2
  122. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +5 -0
  123. package/dist/src/storage/workspace-permissions-health.js +64 -0
  124. package/dist/src/storage/workspace-permissions.js +51 -0
  125. package/package.json +9 -2
  126. package/schemas/models/model-config-compatibility.v1.schema.json +4 -0
  127. package/tools/agents/deploy-agents.mjs +15 -0
  128. package/tools/agents/providers/base-contract.mjs +7 -1
  129. package/tools/agents/providers/base-files.mjs +2 -1
  130. package/tools/agents/providers/base-flat-artifacts.mjs +6 -3
  131. package/tools/agents/providers/base-inventory.mjs +35 -13
  132. package/tools/agents/providers/base-models-platforms.mjs +3 -3
  133. package/tools/agents/providers/base-skill-copy.mjs +2 -0
  134. package/tools/agents/providers/base.mjs +1 -1
  135. package/tools/agents/providers/bound-rules-pointer.mjs +21 -0
  136. package/tools/agents/providers/claude-post-deploy.mjs +9 -5
  137. package/tools/agents/providers/codex-post-deploy.mjs +10 -0
  138. package/tools/agents/providers/conductor-data-guard.mjs +35 -11
  139. package/tools/agents/providers/factory-hooks.mjs +43 -0
  140. package/tools/agents/providers/factory.mjs +4 -91
  141. package/tools/agents/providers/muse-hooks.mjs +6 -41
  142. package/tools/agents/providers/muse-prompt-discovery.mjs +18 -0
  143. package/tools/agents/providers/packaged-codex-agents.mjs +48 -0
  144. package/tools/agents/providers/provider-prepare-coordinator.mjs +15 -10
  145. package/tools/agents/providers/rule-delivery-surface.mjs +10 -7
  146. package/tools/agents/providers/rule-deployment-commit.mjs +10 -0
  147. package/tools/agents/providers/rule-presentation.mjs +6 -5
  148. package/tools/agents/providers/rule-projection.mjs +10 -2
  149. package/tools/agents/providers/rule-startup.mjs +8 -1
  150. package/tools/agents/providers/stale-artifact-prune.mjs +9 -8
  151. package/tools/cli/decision-offload-report.mjs +7 -2
  152. package/tools/plugin/issue-template-copies.mjs +24 -0
  153. package/tools/plugin/package-plugins.mjs +11 -3
  154. package/tools/ralph-external/lib/factory-adapter.mjs +7 -8
  155. package/tools/ralph-external/lib/worker-artifacts.mjs +4 -2
  156. package/tools/ralph-external/lib/worker-capture.mjs +157 -0
  157. package/tools/ralph-external/lib/worker-final.mjs +43 -8
  158. package/tools/ralph-external/lib/worker-health.mjs +3 -0
  159. package/tools/ralph-external/lib/worker-invocation-processes.mjs +9 -6
  160. package/tools/ralph-external/lib/worker-launch-cli.mjs +20 -2
  161. package/tools/ralph-external/lib/worker-process-identity.mjs +30 -0
  162. package/tools/ralph-external/lib/worker-prompt.mjs +35 -0
  163. package/tools/ralph-external/lib/worker-retry-evidence.mjs +87 -6
  164. package/tools/ralph-external/lib/worker-run-directory-refusal.mjs +8 -0
  165. package/tools/ralph-external/lib/worker-termination.mjs +56 -6
  166. package/tools/ralph-external/process-monitor.mjs +12 -18
  167. package/tools/ralph-external/session-launcher.mjs +53 -36
  168. package/vscode-extension/schemas/aiwg.config.v1.json +15 -0
@@ -0,0 +1,44 @@
1
+ // Workspace/group environment protocol shared by worker launchers and the host census.
2
+ import path from 'node:path';
3
+ import { realpathSync } from 'node:fs';
4
+ import { createHash } from 'node:crypto';
5
+ import { WORKER_INVOCATION_MARKER } from './worker-invocation-marker.mjs';
6
+
7
+ export const WORKER_WORKSPACE_MARKER = 'AIWG_WORKER_WORKSPACE';
8
+ export const WORKER_GROUP_MARKER = 'AIWG_WORKER_GROUP';
9
+
10
+ export function workerWorkspace(value) {
11
+ if (typeof value !== 'string' || !path.isAbsolute(value) || value.includes('\0')) return undefined;
12
+ try { return realpathSync(value); } catch { return path.normalize(value); }
13
+ }
14
+
15
+ export function workerAttributionEnvironment(invocationId, workspace, group) {
16
+ const canonical = workerWorkspace(workspace);
17
+ if (typeof invocationId !== 'string' || !invocationId || /[\0\r\n]/.test(invocationId)) {
18
+ throw new Error('Worker attribution requires a non-empty invocation ID');
19
+ }
20
+ if (!canonical || typeof group !== 'string' || !group || /[\0\r\n]/.test(group)) {
21
+ throw new Error('Worker attribution requires an absolute workspace and a non-empty group');
22
+ }
23
+ return { [WORKER_INVOCATION_MARKER]: invocationId,
24
+ [WORKER_WORKSPACE_MARKER]: canonical, [WORKER_GROUP_MARKER]: group };
25
+ }
26
+
27
+ export function directWorkerEnvironment(invocation) {
28
+ const id = invocation.invocationId ?? createHash('sha256').update(JSON.stringify([
29
+ invocation.cwd, invocation.selected, invocation.finalPath, invocation.briefDigest,
30
+ ])).digest('hex');
31
+ return workerAttributionEnvironment(id, invocation.cwd, invocation.selected.group);
32
+ }
33
+
34
+ export function readWorkerAttribution(environment) {
35
+ const fields = environment.split('\0');
36
+ const read = name => {
37
+ const values = fields.filter(field => field.startsWith(`${name}=`)).map(field => field.slice(name.length + 1));
38
+ return values.length === 1 ? values[0] : undefined;
39
+ };
40
+ const invocation = read(WORKER_INVOCATION_MARKER);
41
+ const workspace = workerWorkspace(read(WORKER_WORKSPACE_MARKER));
42
+ const group = read(WORKER_GROUP_MARKER);
43
+ return { invocation, ...(workspace && group && !/[\0\r\n]/.test(group) ? { workspace, group } : {}) };
44
+ }
@@ -1,6 +1,7 @@
1
1
  // Shares atomic replacement and serialization across worker configuration owners.
2
+ import { workspaceFileMode, preserveReplacementMode } from '../storage/workspace-permissions.js';
2
3
  import { AsyncLocalStorage } from 'node:async_hooks';
3
- import { mkdir, writeFile, rename, unlink, stat } from 'node:fs/promises';
4
+ import { mkdir, writeFile, rename, unlink } from 'node:fs/promises';
4
5
  import { statSync, readFileSync } from 'node:fs';
5
6
  import { randomBytes } from 'node:crypto';
6
7
  import { dirname, join } from 'node:path';
@@ -24,17 +25,10 @@ export async function atomicConfigWrite(file, content, assertOwned) {
24
25
  assertOwned?.();
25
26
  await mkdir(dirname(file), { recursive: true });
26
27
  const temporary = `${file}.${randomBytes(6).toString('hex')}.tmp`;
27
- let mode = 0o600;
28
- try {
29
- mode = (await stat(file)).mode;
30
- }
31
- catch (error) {
32
- if (error.code !== 'ENOENT')
33
- throw error;
34
- }
35
28
  try {
36
29
  assertOwned?.();
37
- await writeFile(temporary, content, { encoding: 'utf8', mode });
30
+ await writeFile(temporary, content, { encoding: 'utf8', mode: workspaceFileMode(file), flag: 'wx' });
31
+ await preserveReplacementMode(temporary, file);
38
32
  assertOwned?.();
39
33
  await rename(temporary, file);
40
34
  }
@@ -19,7 +19,7 @@
19
19
  * ACCIDENTAL hazard — a stray symlink, a hard link, loose permissions left
20
20
  * by another tool, a previous crash's partial write — all under the
21
21
  * assumption that the artifact root is owned and written by the SAME local
22
- * user running `aiwg`. It does not and cannot defend against a HOSTILE
22
+ * user running `aiwg`, or its stat-verified shared workspace group. It does not and cannot defend against a HOSTILE
23
23
  * process running as that same user: such a process already has read/write
24
24
  * access to everything the ledger could protect. Appenders, rotation and
25
25
  * readers share the existing cross-process directory-lock helper. There is
@@ -52,6 +52,7 @@
52
52
  * attribution-to-append stage starts once the deadline has fired. An append
53
53
  * already waiting for the ledger lock can still complete after that deadline.
54
54
  */
55
+ import { workspaceFileMode, workspaceDirectoryMode, workspacePermissionsAllowed, preserveReplacementMode } from '../storage/workspace-permissions.js';
55
56
  import { randomUUID, createHash } from 'node:crypto';
56
57
  import { constants as fsConstants, createReadStream, existsSync } from 'node:fs';
57
58
  import { lstat, mkdir, open, readdir, rename, rm } from 'node:fs/promises';
@@ -120,8 +121,6 @@ export const MAX_RECORD_TEXT_BYTES = 600;
120
121
  export const MAX_LEDGER_RECORD_BYTES = 4000;
121
122
  /** Bounds how long `recordDecisionAsk` waits on attribution resolution and the write. On timeout the outcome is reported as unknown, not "abandoned" — see the module doc comment. */
122
123
  export const DECISION_LEDGER_RECORD_TIMEOUT_MS = 250;
123
- const LEDGER_DIR_MODE = 0o700;
124
- const LEDGER_FILE_MODE = 0o600;
125
124
  const LEDGER_LOCK_TIMEOUT_MS = 30_000;
126
125
  const IS_WINDOWS = process.platform === 'win32';
127
126
  const HAS_O_NOFOLLOW = typeof fsConstants.O_NOFOLLOW === 'number';
@@ -316,14 +315,14 @@ function currentUid() {
316
315
  /**
317
316
  * Create (if needed) the owner-only `decision` directory and verify it is
318
317
  * safe to use: a real directory (not a symlink), and on POSIX owned by the
319
- * current user. An existing directory that fails either check is never
318
+ * current user or its stat-verified workspace group. An existing directory that fails either check is never
320
319
  * modified (no chmod) — recording is skipped.
321
320
  */
322
321
  async function ensurePrivateDecisionDir(projectRoot, warn) {
323
322
  const artifactRoot = projectAiwgWritePath(projectRoot);
324
323
  const decisionDir = join(artifactRoot, DECISION_LEDGER_DIR_NAME);
325
324
  try {
326
- await mkdir(decisionDir, { recursive: true, mode: LEDGER_DIR_MODE });
325
+ await mkdir(decisionDir, { recursive: true, mode: workspaceDirectoryMode(decisionDir) });
327
326
  }
328
327
  catch (error) {
329
328
  warn(`warning: cannot create decision ledger directory: ${errorMessage(error)}`);
@@ -343,7 +342,7 @@ async function ensurePrivateDecisionDir(projectRoot, warn) {
343
342
  }
344
343
  if (!IS_WINDOWS) {
345
344
  const uid = currentUid();
346
- if (uid !== null && stat.uid !== uid) {
345
+ if (uid !== null && stat.uid !== uid && !((stat.mode & 0o070) !== 0 && workspacePermissionsAllowed(decisionDir, stat))) {
347
346
  warn('warning: decision ledger directory is not owned by the current user; skipping record');
348
347
  return null;
349
348
  }
@@ -355,7 +354,7 @@ async function ensurePrivateDecisionDir(projectRoot, warn) {
355
354
  * retention) and verify it is a regular file with exactly one hard link (rejects a
356
355
  * pre-planted hard link to an unrelated file, which `O_NOFOLLOW` alone does
357
356
  * not catch), and on POSIX owned by the current user with no group/other
358
- * permission bits. `O_NOFOLLOW` is applied when the platform defines it
357
+ * permission bits outside a matching shared workspace group. `O_NOFOLLOW` is applied when the platform defines it
359
358
  * (refusing a pre-planted symlink at open time on POSIX); on platforms
360
359
  * without it (Windows) a prior plain `lstat` is the only symlink check —
361
360
  * see the module doc comment on the trust boundary. A file that fails any
@@ -378,7 +377,7 @@ async function openPrivateLedgerFile(ledgerPath, warn, flags = fsConstants.O_APP
378
377
  }
379
378
  let handle;
380
379
  try {
381
- handle = await open(ledgerPath, flags | (HAS_O_NOFOLLOW ? fsConstants.O_NOFOLLOW : 0), LEDGER_FILE_MODE);
380
+ handle = await open(ledgerPath, flags | (HAS_O_NOFOLLOW ? fsConstants.O_NOFOLLOW : 0), workspaceFileMode(ledgerPath));
382
381
  }
383
382
  catch (error) {
384
383
  warn(`warning: cannot open decision ledger file: ${errorMessage(error)}`);
@@ -398,12 +397,12 @@ async function openPrivateLedgerFile(ledgerPath, warn, flags = fsConstants.O_APP
398
397
  }
399
398
  if (!IS_WINDOWS) {
400
399
  const uid = currentUid();
401
- if (uid !== null && stat.uid !== uid) {
400
+ if (uid !== null && stat.uid !== uid && !((stat.mode & 0o070) !== 0 && workspacePermissionsAllowed(ledgerPath, stat))) {
402
401
  warn('warning: decision ledger file is not owned by the current user; skipping record');
403
402
  await handle.close();
404
403
  return null;
405
404
  }
406
- if ((stat.mode & 0o077) !== 0) {
405
+ if (!workspacePermissionsAllowed(ledgerPath, stat)) {
407
406
  warn('warning: decision ledger file has group or other permission bits set; skipping record');
408
407
  await handle.close();
409
408
  return null;
@@ -516,7 +515,7 @@ async function privateArchiveDirectory(root, target, create) {
516
515
  current = join(current, part);
517
516
  if (create) {
518
517
  try {
519
- await mkdir(current, { mode: LEDGER_DIR_MODE });
518
+ await mkdir(current, { mode: workspaceDirectoryMode(current) });
520
519
  if (!IS_WINDOWS)
521
520
  await syncDirectory(dirname(current));
522
521
  }
@@ -535,9 +534,9 @@ async function privateArchiveDirectory(root, target, create) {
535
534
  throw error;
536
535
  }
537
536
  // archive/ is shared with the activity log and may already be readable.
538
- // Its decision/ subtree (and any nested directories) must be private.
537
+ // Its decision/ subtree must be private or match the shared workspace group.
539
538
  const modeMask = current === join(root, 'archive') ? 0o022 : 0o077;
540
- if (!info.isDirectory() || (!IS_WINDOWS && (info.uid !== currentUid() || (info.mode & modeMask) !== 0))) {
539
+ if (!info.isDirectory() || (!IS_WINDOWS && ((info.uid !== currentUid() || (info.mode & modeMask) !== 0) && !((info.mode & 0o070) !== 0 && workspacePermissionsAllowed(current, info))))) {
541
540
  throw new Error(`Unsafe decision archive directory (requires a private, owned real directory): ${current}`);
542
541
  }
543
542
  }
@@ -602,7 +601,7 @@ export async function rotateDecisionLedger(options) {
602
601
  if (!archived.length)
603
602
  return result;
604
603
  await privateArchiveDirectory(artifactRoot, dirname(archivePath), true);
605
- const archive = await open(archivePath, 'wx', LEDGER_FILE_MODE);
604
+ const archive = await open(archivePath, 'wx', workspaceFileMode(archivePath));
606
605
  archiveCreated = true;
607
606
  try {
608
607
  await writeFully(archive, Buffer.concat(archived));
@@ -613,9 +612,10 @@ export async function rotateDecisionLedger(options) {
613
612
  }
614
613
  if (!IS_WINDOWS)
615
614
  await syncDirectory(dirname(archivePath));
616
- const replacement = await open(tempPath, 'wx', LEDGER_FILE_MODE);
615
+ const replacement = await open(tempPath, 'wx', workspaceFileMode(ledgerPath));
617
616
  try {
618
617
  await writeFully(replacement, Buffer.concat(kept));
618
+ await preserveReplacementMode(tempPath, ledgerPath);
619
619
  await replacement.sync();
620
620
  }
621
621
  finally {
@@ -6,6 +6,7 @@
6
6
  * opportunity denominator. Completed-call records remain in ledger.ts; the
7
7
  * shared correlation id joins the two append-only journals.
8
8
  */
9
+ import { workspaceFileMode, workspaceDirectoryMode, workspacePermissionsAllowed } from '../storage/workspace-permissions.js';
9
10
  import { randomUUID } from 'node:crypto';
10
11
  import { constants as fsConstants, createReadStream } from 'node:fs';
11
12
  import { lstat, mkdir, open } from 'node:fs/promises';
@@ -22,8 +23,6 @@ import { ATTRIBUTION_FIELD_PATTERN, decisionLedgerHistory, DECISION_LEDGER_RECOR
22
23
  export const DECISION_OPPORTUNITY_SCHEMA = 'aiwg-decision-opportunity/v1';
23
24
  export const DECISION_OFFLOAD_SNAPSHOT_SCHEMA = 'aiwg-decision-offload-snapshot/v1';
24
25
  const OPPORTUNITY_FILE = 'opportunities.jsonl';
25
- const DIR_MODE = 0o700;
26
- const FILE_MODE = 0o600;
27
26
  const MAX_OPPORTUNITY_RECORD_BYTES = 4000;
28
27
  export const DECISION_OPPORTUNITY_RECORD_TIMEOUT_MS = DECISION_LEDGER_RECORD_TIMEOUT_MS;
29
28
  const TIMED_OUT = Symbol('decision-offload-timeout');
@@ -161,22 +160,22 @@ export async function appendDecisionOpportunity(record, projectRoot, warn = mess
161
160
  try {
162
161
  const directory = projectAiwgWritePath(projectRoot, 'decision');
163
162
  const file = path.join(directory, OPPORTUNITY_FILE);
164
- await mkdir(directory, { recursive: true, mode: DIR_MODE });
163
+ await mkdir(directory, { recursive: true, mode: workspaceDirectoryMode(directory) });
165
164
  const dirStat = await lstat(directory);
166
- if (!dirStat.isDirectory() || dirStat.isSymbolicLink() || (dirStat.mode & 0o077) !== 0)
165
+ if (!dirStat.isDirectory() || dirStat.isSymbolicLink() || !workspacePermissionsAllowed(directory, dirStat))
167
166
  throw new Error('unsafe opportunity directory');
168
167
  try {
169
168
  const fileStat = await lstat(file);
170
- if (!fileStat.isFile() || fileStat.isSymbolicLink() || fileStat.nlink !== 1 || (fileStat.mode & 0o077) !== 0)
169
+ if (!fileStat.isFile() || fileStat.isSymbolicLink() || fileStat.nlink !== 1 || !workspacePermissionsAllowed(file, fileStat))
171
170
  throw new Error('unsafe opportunity file');
172
171
  }
173
172
  catch (error) {
174
173
  if (error.code !== 'ENOENT')
175
174
  throw error;
176
175
  }
177
- handle = await open(file, fsConstants.O_APPEND | fsConstants.O_CREAT | fsConstants.O_WRONLY | (fsConstants.O_NOFOLLOW ?? 0), FILE_MODE);
176
+ handle = await open(file, fsConstants.O_APPEND | fsConstants.O_CREAT | fsConstants.O_WRONLY | (fsConstants.O_NOFOLLOW ?? 0), workspaceFileMode(file));
178
177
  const opened = await handle.stat();
179
- if (!opened.isFile() || opened.nlink !== 1 || (opened.mode & 0o077) !== 0)
178
+ if (!opened.isFile() || opened.nlink !== 1 || !workspacePermissionsAllowed(file, opened))
180
179
  throw new Error('unsafe opened opportunity file');
181
180
  await writeFully(handle, Buffer.from(line, 'utf8'));
182
181
  return true;
@@ -0,0 +1,62 @@
1
+ // Run delivery git operations with explicit identity, signing, transport and a bounded child environment.
2
+ import { execFile } from 'node:child_process';
3
+ import { promisify } from 'node:util';
4
+ import path from 'node:path';
5
+ import { helperEnvironment, HELPER_ENV_ALLOWLIST } from '../process/cli-command.mjs';
6
+ const execute = promisify(execFile);
7
+ export async function command(cwd, executable, args) {
8
+ try {
9
+ const { stdout } = await execute(executable, args, { cwd, encoding: 'utf8', timeout: 120_000, maxBuffer: 8 * 1024 * 1024,
10
+ env: helperEnvironment(process.env, [...HELPER_ENV_ALLOWLIST, 'SSH_AUTH_SOCK', 'GNUPGHOME', 'GPG_TTY']) });
11
+ return stdout.trim();
12
+ }
13
+ catch {
14
+ throw new Error(`Delivery ${path.basename(executable)} operation failed; inspect repository state before retrying`);
15
+ }
16
+ }
17
+ export const git = (cwd, ...args) => command(cwd, 'git', args);
18
+ export function signingEnabled(delivery) {
19
+ const required = delivery?.require_signed_commits || delivery?.merge === 'local-signed';
20
+ const signing = delivery?.signing;
21
+ if (required && !signing?.key)
22
+ throw new Error('Signed delivery requires delivery.signing.key');
23
+ return Boolean(required || (signing?.enforce !== 'tags' && (signing?.key || signing?.key_file)));
24
+ }
25
+ export function commitOptions(delivery, project = process.cwd()) {
26
+ const options = [];
27
+ for (const [key, value] of [['user.name', delivery?.committer?.name], ['user.email', delivery?.committer?.email]]) {
28
+ if (value)
29
+ options.push('-c', `${key}=${value}`);
30
+ }
31
+ if (signingEnabled(delivery)) {
32
+ const signing = delivery.signing;
33
+ if (!signing.key || !delivery?.committer?.name || !delivery.committer.email)
34
+ throw new Error('Signed delivery requires signing.key and committer.name/email');
35
+ const format = signing.format ?? 'openpgp';
36
+ options.push('-c', `gpg.format=${format}`, '-c', `user.signingkey=${signing.key_file ? path.resolve(project, signing.key_file) : signing.key}`, '-c', 'commit.gpgsign=true');
37
+ if (signing.program)
38
+ options.push('-c', `gpg.${format}.program=${/[\\/]/.test(signing.program) ? path.resolve(project, signing.program) : signing.program}`);
39
+ }
40
+ else
41
+ options.push('-c', 'commit.gpgsign=false');
42
+ return options;
43
+ }
44
+ export async function verifyCommit(cwd, sha, delivery, project = cwd) {
45
+ if (!signingEnabled(delivery))
46
+ return;
47
+ const result = await git(cwd, ...commitOptions(delivery, project), 'show', '-s', '--format=%G?%x00%GF%x00%GP%x00%an%x00%ae%x00%cn%x00%ce', sha);
48
+ const [status, key, primaryKey, author, email, committer, committerEmail] = result.split('\0');
49
+ const identity = delivery.committer;
50
+ if (!['G', 'U'].includes(status) || ![key, primaryKey].includes(delivery.signing.key) || author !== identity.name || email !== identity.email || committer !== identity.name || committerEmail !== identity.email) {
51
+ throw new Error('Commit does not satisfy configured signature and author/committer identity');
52
+ }
53
+ }
54
+ export async function push(cwd, project, config, remote, refspec, upstream = false) {
55
+ const helper = config.remotes?.transport?.helper;
56
+ // Helper follows the established helper contract: push options/refspec, configured primary remote owned by helper.
57
+ if (helper)
58
+ await command(cwd, path.resolve(project, helper), [...(upstream ? ['-u'] : []), refspec]);
59
+ else
60
+ await git(cwd, 'push', ...(upstream ? ['-u'] : []), remote, refspec);
61
+ }
62
+ //# sourceMappingURL=git.js.map
@@ -0,0 +1,151 @@
1
+ // Open tracker PRs and execute optional local merges using configured signing and transport policy.
2
+ import { mkdtemp, rm, readFile } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { readAiwgConfig, resolveDelivery, resolveRemotes, resolveProject, resolveProjectHandling } from '../config/aiwg-config.js';
6
+ import { sensitiveInputOptions } from '../auth/sensitive-input.js';
7
+ import { deliveryTracker } from './tracker.js';
8
+ import { commitOptions, git, push, signingEnabled, verifyCommit } from './git.js';
9
+ import { warnTemplateSections } from './template-sections.js';
10
+ async function branchCommits(cwd, base, head, config) {
11
+ if (!signingEnabled(config.delivery))
12
+ return;
13
+ for (const sha of (await git(cwd, 'rev-list', `${base}..${head}`)).split('\n').filter(Boolean))
14
+ await verifyCommit(cwd, sha, config.delivery);
15
+ }
16
+ export async function openPr(cwd, config, client, options) {
17
+ const policy = resolveDelivery(config.delivery);
18
+ if (policy.mode !== 'pr-required')
19
+ throw new Error('Opening a PR requires delivery.mode=pr-required');
20
+ if (!options.title)
21
+ throw new Error('open requires --title');
22
+ warnTemplateSections(options.body ?? '', 'agentic/code/addons/aiwg-utils/templates/pull-requests/description.md');
23
+ const remote = resolveRemotes(config.remotes).primary;
24
+ const head = options.head ?? await git(cwd, 'symbolic-ref', '--short', 'HEAD');
25
+ await git(cwd, 'check-ref-format', '--branch', head);
26
+ if (head === policy.default_branch)
27
+ throw new Error('PR head must differ from the default branch');
28
+ if (await git(cwd, 'symbolic-ref', '--short', 'HEAD') !== head)
29
+ throw new Error('PR head must be the checked out branch');
30
+ await client.verifyActor();
31
+ const identity = commitOptions(config.delivery, cwd);
32
+ if (options.commitMessageFile) {
33
+ if (!(await git(cwd, 'diff', '--cached', '--name-only')))
34
+ throw new Error('Nothing staged to commit');
35
+ await git(cwd, ...identity, 'commit', '-F', path.resolve(cwd, options.commitMessageFile));
36
+ }
37
+ const sha = await git(cwd, 'rev-parse', '--verify', `refs/heads/${head}^{commit}`);
38
+ const current = await git(cwd, 'rev-parse', 'HEAD');
39
+ if (current !== sha)
40
+ throw new Error('PR head must be the current checked out commit');
41
+ await git(cwd, 'fetch', remote);
42
+ await branchCommits(cwd, `refs/remotes/${remote}/${policy.default_branch}`, sha, config);
43
+ await push(cwd, cwd, config, remote, head, true);
44
+ return client.repositoryRequest('POST', '/pulls', { title: options.title, body: options.body ?? '', head, base: policy.default_branch });
45
+ }
46
+ export async function mergePr(cwd, config, client, number, options = {}) {
47
+ if (!/^[1-9][0-9]*$/.test(number))
48
+ throw new Error('merge requires a positive PR number');
49
+ const policy = resolveDelivery(config.delivery);
50
+ const remotes = resolveRemotes(config.remotes);
51
+ // Resolve invalid signing policy before any tracker or git mutations.
52
+ const identity = commitOptions(config.delivery, cwd);
53
+ const signed = signingEnabled(config.delivery);
54
+ if (signed && policy.merge === 'tracker')
55
+ throw new Error('Configured signing requires a local merge route; ask Steward to set delivery.merge');
56
+ if (options.mirror && (!remotes.secondary.some(remote => remote.name === options.mirror) || !resolveProjectHandling(resolveProject(config.project)).mirror))
57
+ throw new Error('Mirror must be a configured secondary remote permitted by project handling');
58
+ await client.verifyActor();
59
+ const pr = await client.repositoryRequest('GET', `/pulls/${number}`);
60
+ if (pr.state !== 'open')
61
+ throw new Error('PR is not open');
62
+ if (pr.base.ref !== policy.default_branch)
63
+ throw new Error('PR must target the configured default branch');
64
+ if (!/^[a-f0-9]{40,64}$/.test(pr.head.sha))
65
+ throw new Error('Tracker returned an invalid head SHA');
66
+ if (policy.merge === 'tracker') {
67
+ const style = policy.merge_style;
68
+ const method = style === 'squash' ? 'squash' : style === 'rebase-merge' ? 'rebase' : 'merge';
69
+ if (client.provider === 'github' && style === 'fast-forward-only')
70
+ throw new Error('GitHub does not support tracker fast-forward-only merges; use delivery.merge=local');
71
+ const result = await client.repositoryRequest(client.provider === 'github' ? 'PUT' : 'POST', `/pulls/${number}/merge`, client.provider === 'github'
72
+ ? { merge_method: method, sha: pr.head.sha } : { Do: style === 'fast-forward-only' ? 'fast-forward-only' : style === 'rebase-merge' ? 'rebase-merge' : method, head_commit_id: pr.head.sha });
73
+ if (result.merged === false)
74
+ throw new Error('Tracker refused the PR merge');
75
+ return result;
76
+ }
77
+ await git(cwd, 'fetch', remotes.primary);
78
+ await git(cwd, 'fetch', remotes.primary, pr.head.sha);
79
+ const mainRef = `refs/remotes/${remotes.primary}/${policy.default_branch}`;
80
+ const main = await git(cwd, 'rev-parse', mainRef);
81
+ const base = await git(cwd, 'merge-base', pr.head.sha, main);
82
+ const tree = (ref) => git(cwd, 'rev-parse', `${ref}^{tree}`);
83
+ if (await tree(base) !== await tree(main))
84
+ throw new Error('Current main tree differs from branch base; synchronize and verify first');
85
+ if (!(await git(cwd, 'rev-list', `${main}..${pr.head.sha}`)))
86
+ throw new Error('PR has no branch commits to merge');
87
+ await branchCommits(cwd, main, pr.head.sha, config);
88
+ const scratch = await mkdtemp(path.join(os.tmpdir(), 'aiwg-merge-'));
89
+ const worktree = path.join(scratch, 'worktree');
90
+ let added = false;
91
+ try {
92
+ await git(cwd, 'worktree', 'add', '--detach', worktree, main);
93
+ added = true;
94
+ await git(worktree, ...identity, 'merge', '--no-ff', ...(signed ? ['-S'] : []), '-m', `merge: ${pr.title} (#${number})`, pr.head.sha);
95
+ const merged = await git(worktree, 'rev-parse', 'HEAD');
96
+ if (await tree(merged) !== await tree(pr.head.sha))
97
+ throw new Error('Merge tree differs from verified PR head');
98
+ await verifyCommit(worktree, merged, config.delivery, cwd);
99
+ // Refuse a changed PR or main before push; the ordinary push also rejects a concurrent non-fast-forward update.
100
+ const latest = await client.repositoryRequest('GET', `/pulls/${number}`);
101
+ if (latest.state !== 'open' || latest.head.sha !== pr.head.sha || latest.base.ref !== pr.base.ref)
102
+ throw new Error('PR changed during merge; retry after verification');
103
+ await git(cwd, 'fetch', remotes.primary);
104
+ if (await git(cwd, 'rev-parse', mainRef) !== main)
105
+ throw new Error('Main changed during merge; synchronize and verify first');
106
+ await push(worktree, cwd, config, remotes.primary, `${merged}:refs/heads/${policy.default_branch}`);
107
+ await client.repositoryRequest('PATCH', `/pulls/${number}`, { state: 'closed' });
108
+ await git(cwd, 'fetch', remotes.primary);
109
+ if (await git(cwd, 'rev-parse', mainRef) !== merged)
110
+ throw new Error('Remote default branch differs from the local merge');
111
+ if (options.mirror)
112
+ await git(cwd, 'push', options.mirror, `${merged}:refs/heads/${policy.default_branch}`);
113
+ return { number: Number(number), merged, signed, mode: policy.merge };
114
+ }
115
+ finally {
116
+ try {
117
+ if (added)
118
+ await git(cwd, 'worktree', 'remove', '--force', worktree);
119
+ }
120
+ finally {
121
+ await rm(scratch, { recursive: true, force: true });
122
+ }
123
+ }
124
+ }
125
+ export async function main(args, cwd = process.cwd()) {
126
+ const config = await readAiwgConfig(cwd);
127
+ if (!config)
128
+ throw new Error('PR delivery requires .aiwg/aiwg.config');
129
+ const flags = new Map();
130
+ const positional = [];
131
+ const allowed = ['title', 'body-file', 'head', 'commit-message-file', 'mirror', 'repo', 'api-url', 'token-store', 'token-env'];
132
+ for (let i = 0; i < args.length; i++) {
133
+ if (!args[i].startsWith('--')) {
134
+ positional.push(args[i]);
135
+ continue;
136
+ }
137
+ const key = args[i].slice(2);
138
+ if (!allowed.includes(key) || !args[i + 1] || args[i + 1].startsWith('--') || flags.has(key))
139
+ throw new Error(`Invalid PR option: --${key}`);
140
+ flags.set(key, args[++i]);
141
+ }
142
+ if (!['open', 'merge'].includes(positional[0]) || positional.length !== (positional[0] === 'merge' ? 2 : 1))
143
+ throw new Error('Usage: aiwg run skill aiwg-pr -- open --title <title> --body-file <path> [--commit-message-file <path>] | merge <number> [--mirror <remote>]');
144
+ const client = await deliveryTracker(cwd, config, { repo: flags.get('repo'), apiUrl: flags.get('api-url'), source: sensitiveInputOptions(args, 'token') });
145
+ const options = { title: flags.get('title'), head: flags.get('head'), commitMessageFile: flags.get('commit-message-file'), mirror: flags.get('mirror'),
146
+ body: flags.has('body-file') ? await readFile(path.resolve(cwd, flags.get('body-file')), 'utf8') : undefined };
147
+ const result = positional[0] === 'open' ? await openPr(cwd, config, client, options) : await mergePr(cwd, config, client, positional[1], options);
148
+ console.log(JSON.stringify(result, null, 2));
149
+ return 0;
150
+ }
151
+ //# sourceMappingURL=pr.js.map
@@ -0,0 +1,56 @@
1
+ // Advise issue and PR composers about missing sections using the shipped template headings.
2
+ import { readFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { findPackageRoot } from '../cli/find-package-root.js';
6
+ function headings(markdown) {
7
+ const result = [];
8
+ let fence = '';
9
+ let optional = false;
10
+ for (const line of markdown.split(/\r?\n/)) {
11
+ const marker = line.match(/^\s{0,3}(`{3,}|~{3,})/);
12
+ if (marker) {
13
+ if (!fence)
14
+ fence = marker[1];
15
+ else if (marker[1][0] === fence[0] && marker[1].length >= fence.length)
16
+ fence = '';
17
+ continue;
18
+ }
19
+ if (fence)
20
+ continue;
21
+ const match = line.match(/^##[ \t]+(.+?)[ \t]*#*[ \t]*$/);
22
+ if (match) {
23
+ result.push({ title: match[1], optional: optional || /\(optional\b|<!--\s*optional\s*-->/i.test(match[1]) });
24
+ optional = false;
25
+ }
26
+ else if (line.trim()) {
27
+ optional = /^\s*<!--\s*optional\s*-->\s*$/i.test(line);
28
+ }
29
+ }
30
+ return result;
31
+ }
32
+ const headingKey = (title) => title.replace(/<!--.*?-->/g, '')
33
+ .replace(/\s+\(.*$/, '').trim().replace(/\s+/g, ' ').toLowerCase();
34
+ export function missingTemplateSections(body, template) {
35
+ const present = new Set(headings(body).map(heading => headingKey(heading.title)));
36
+ return headings(template).filter(heading => !heading.optional && !present.has(headingKey(heading.title)))
37
+ .map(heading => heading.title);
38
+ }
39
+ export function warnTemplateSections(body, template, warn = console.warn) {
40
+ const root = process.env.AIWG_ROOT ?? findPackageRoot(path.dirname(fileURLToPath(import.meta.url)));
41
+ let content;
42
+ try {
43
+ if (!root && !path.isAbsolute(template))
44
+ throw new Error('AIWG package root unavailable');
45
+ content = readFileSync(path.resolve(root ?? '.', template), 'utf8');
46
+ }
47
+ catch {
48
+ warn(`Template warning: could not read ${template}; required sections were not checked.`);
49
+ return [];
50
+ }
51
+ const missing = missingTemplateSections(body, content);
52
+ if (missing.length)
53
+ warn(`Template warning (${path.basename(template)}): missing required sections: ${missing.join(', ')}`);
54
+ return missing;
55
+ }
56
+ //# sourceMappingURL=template-sections.js.map
@@ -0,0 +1,33 @@
1
+ import { resolveRemotes } from '../config/aiwg-config.js';
2
+ import { LiveIssueClient } from '../issues/live.js';
3
+ import { trackerToken } from '../issues/tracker-policy.js';
4
+ import { git } from './git.js';
5
+ export async function deliveryTracker(cwd, config, options = {}) {
6
+ const remotes = resolveRemotes(config.remotes);
7
+ if (remotes.issue_provider === 'local' || remotes.issue_tracker === 'local')
8
+ throw new Error('PR and external issue writes require an external tracker');
9
+ let provider = remotes.issue_provider;
10
+ let repo = options.repo;
11
+ let apiUrl = options.apiUrl;
12
+ if (!repo || !apiUrl || !provider) {
13
+ const remote = remotes.issue_tracker;
14
+ const url = remote.includes('://') || remote.includes('@') ? remote : await git(cwd, 'remote', 'get-url', remote);
15
+ const normalized = url.replace(/^([^@]+@)([^:]+):/, 'ssh://$1$2/');
16
+ let parsed;
17
+ try {
18
+ parsed = new URL(normalized);
19
+ }
20
+ catch {
21
+ throw new Error('Cannot resolve tracker remote; supply --repo and --api-url with an explicit issue_provider');
22
+ }
23
+ if ((parsed.protocol === 'https:' || parsed.protocol === 'http:') && (parsed.username || parsed.password))
24
+ throw new Error('Tracker remote URLs must not contain credentials');
25
+ provider ??= parsed.hostname === 'github.com' ? 'github' : 'gitea';
26
+ repo ??= parsed.pathname.replace(/^\//, '').replace(/\.git$/, '');
27
+ const protocol = parsed.protocol === 'http:' ? 'http:' : 'https:';
28
+ apiUrl ??= provider === 'github' ? parsed.hostname === 'github.com' ? 'https://api.github.com' : `${protocol}//${parsed.host}/api/v3` : `${protocol}//${parsed.host}/api/v1`;
29
+ }
30
+ const token = await trackerToken(provider, remotes.tracker_actor, options.source);
31
+ return new LiveIssueClient({ provider, repo, apiUrl, token, actor: remotes.tracker_actor });
32
+ }
33
+ //# sourceMappingURL=tracker.js.map
@@ -137,7 +137,7 @@ export function interviewQuestions(context, answers = {}) {
137
137
  questions[questions.length - 1].questionId = questionId('locations', 'credential-source', project.root, 'jev');
138
138
  add('capabilities', 'jev-options', 'Optional Jev settings as JSON: region, endpoint, verify. Verification sends a billable request at apply.', null, [null], '--region <r> --endpoint <url> --verify', 'policy', project.root, 'jev', true);
139
139
  }
140
- add('capabilities', 'signing', 'Require signed delivery commits?', false, [true, false], '--require-signed-commits --signing-format --signing-key --signing-enforce', 'policy', project.root, undefined, true);
140
+ add('capabilities', 'signing', 'Optional: require signed delivery commits? Signed local merges are recommended where permitted; skip preserves unsigned delivery. Set up with aiwg steward signed-merges.', false, [true, false], '--require-signed-commits --signing-format --signing-key --signing-enforce', 'policy', project.root, undefined, true);
141
141
  add('capabilities', 'delivery', 'Delivery mode and branch protections.', { mode: 'pr-required', force_push_policy: 'never' }, [false, { mode: 'pr-required', force_push_policy: 'never' }], '--delivery-mode --default-branch --require-ci-green --auto-close-issues --issue-comment-on-cycle --force-push-policy', 'policy', project.root, undefined, true);
142
142
  add('capabilities', 'tracker', 'Issue tracker provider and remotes.', null, ['gitea', 'github', 'local'].map(issue_provider => ({ issue_provider })), '--issue-provider gitea|github|local', 'policy', project.root, undefined, !context.unknownRemote, !!context.unknownRemote);
143
143
  }