@principles/workbuddy-adapter 0.6.5 → 0.6.7

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.
package/dist/pd-hook.js CHANGED
@@ -71,15 +71,31 @@ function redactStringFields(data) {
71
71
  * core writer, so the WorkBuddy host path carries the host's natural ids
72
72
  * (generation_id → runId/turnId, call_id → toolCallId).
73
73
  */
74
- function workbuddyEventEmitter(stateDir, evidence) {
74
+ function workbuddyEventEmitter(stateDir, evidence, readAdaptiveFact) {
75
75
  return {
76
76
  recordRuntimeActivationsInjected(data) {
77
+ // PRI-1127: attach the Adaptive turn fact to the SAME injection event the
78
+ // Console already reads. Flag-off / Native turns produce NO fact at all,
79
+ // so `adaptive` stays absent (never a fabricated "no append" record).
80
+ // `appendedActivationId` is the FINAL ASSEMBLY basis: a selected id that
81
+ // did not reach activationIds (budget, dropped, failed packing) is not
82
+ // reported as appended.
83
+ const fact = readAdaptiveFact?.() ?? null;
84
+ const adaptive = fact === null
85
+ ? undefined
86
+ : {
87
+ resultCode: `${fact.status}:${fact.reason}`.slice(0, 240),
88
+ scored: fact.sends > 0,
89
+ ...(fact.targetActivationId !== null && data.activationIds.includes(fact.targetActivationId)
90
+ ? { appendedActivationId: fact.targetActivationId }
91
+ : {}),
92
+ };
77
93
  appendEventLogLine(stateDir, {
78
94
  ts: new Date().toISOString(),
79
95
  type: 'runtime_v2_prompt_activations_injected',
80
96
  category: 'injected',
81
97
  sessionId: data.sessionId,
82
- data,
98
+ data: adaptive === undefined ? data : { ...data, adaptive },
83
99
  });
84
100
  // Delivery evidence AFTER the durable source line exists; degrades to a
85
101
  // bounded diagnostic and never affects the hook result.
@@ -434,6 +450,10 @@ export async function processWorkbuddyHookInvocation(rawStdin, channelEventName,
434
450
  // defaults) and must be visible on stderr (rc-9).
435
451
  ? toolSemanticsResolution.warnings.map((warning) => diagnostic('degraded', warning, 're-run this host so it refreshes its persisted tool declaration'))
436
452
  : [diagnostic('degraded', toolSemanticsResolution.reason, toolSemanticsResolution.nextAction)];
453
+ // PRI-1127: capture the real selection outcome for THIS turn so the same
454
+ // injection event can carry the Adaptive fact the Console reads. Absent
455
+ // (flag off / Native) stays absent — no fabricated record.
456
+ let adaptiveTurnFact = null;
437
457
  const adaptive = event.kind === 'before_prompt_build' && flags['host.workbuddy.adaptive_activation']?.enabled === true
438
458
  ? createAdaptivePriorityProviderForConfig(config.effective.config, resolution.workspaceDir, {
439
459
  flag: 'host.workbuddy.adaptive_activation',
@@ -442,12 +462,26 @@ export async function processWorkbuddyHookInvocation(rawStdin, channelEventName,
442
462
  // work well inside that budget, including this process's startup.
443
463
  outerDeadlineAt: Date.now() + Math.max(0, 5000 - Math.round(process.uptime() * 1000)),
444
464
  onDiagnostic: (line) => {
465
+ adaptiveTurnFact = {
466
+ status: line.status,
467
+ reason: line.reason,
468
+ sends: line.sends,
469
+ targetActivationId: line.targetActivationId,
470
+ };
445
471
  if (line.status !== 'selected')
446
472
  evidenceDiagnostics.push(diagnostic(line.status === 'unavailable' ? 'degraded' : 'skipped', `adaptive_selection_${line.status}:${line.reason}`, 'Check Adaptive configuration or use Native assembly.'));
447
473
  },
448
474
  })
449
475
  : undefined;
450
476
  if (adaptive && !adaptive.ok) {
477
+ // `sends: 0` is a fact, not an assumption: no request can leave when the
478
+ // effective configuration cannot build a model (Codex precedent).
479
+ adaptiveTurnFact = {
480
+ status: 'needs_setup',
481
+ reason: adaptive.reason,
482
+ sends: 0,
483
+ targetActivationId: null,
484
+ };
451
485
  evidenceDiagnostics.push(diagnostic('degraded', `adaptive_activation_${adaptive.readiness}:${adaptive.reason}`, adaptive.nextAction));
452
486
  }
453
487
  const result = await createProductionHostRuntime({
@@ -455,7 +489,7 @@ export async function processWorkbuddyHookInvocation(rawStdin, channelEventName,
455
489
  ...(projectDir !== undefined ? { projectDir } : {}),
456
490
  hostKind: 'workbuddy',
457
491
  toolSemantics,
458
- events: workbuddyEventEmitter(stateDir, evidenceContext),
492
+ events: workbuddyEventEmitter(stateDir, evidenceContext, () => adaptiveTurnFact),
459
493
  // SPEC-RULECODE-HOST-PROMOTION-001 C: the V2 rule context provider over
460
494
  // WorkBuddy's own observable trajectory (same-session tool_calls rows
461
495
  // the shared afterToolCall path records). No designGate fact is
@@ -32,7 +32,7 @@
32
32
  import fs from 'node:fs';
33
33
  import path from 'node:path';
34
34
  import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
35
- import { loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
35
+ import { loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, createHostIntentDocReader, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
36
36
  import { WORKBUDDY_TOOL_SEMANTICS, WORKBUDDY_TOOL_SEMANTIC_MAPPINGS } from '../tool-semantics.js';
37
37
  import { catchUpWorkbuddyIngestion } from '../ingestion/catch-up.js';
38
38
  const WORKER_OWNER = 'companion-worker';
@@ -165,6 +165,10 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
165
165
  owner: WORKER_OWNER,
166
166
  effectiveConfig: config.effective,
167
167
  getEnvVar: (name) => process.env[name],
168
+ // PRI-1233 / SPEC §9.2: this worker is where Stage A actually runs
169
+ // for governance-admitted WorkBuddy pains — the neutral host reader
170
+ // must ride along (flag-off = zero filesystem access inside it).
171
+ intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig: config.effective }),
168
172
  });
169
173
  const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
170
174
  diagnostician = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/workbuddy-adapter",
3
- "version": "0.6.5",
3
+ "version": "0.6.7",
4
4
  "description": "WorkBuddy host adapter for Principles Disciple — implements the HostAdapter interface for WorkBuddy's Git Bash command-hook model (ADR-0020 third host, SPEC workbuddy-host-adapter v0.3.0).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -42,9 +42,9 @@
42
42
  "lint": "eslint \"src/**/*.ts\""
43
43
  },
44
44
  "dependencies": {
45
- "@principles/core": "^7.7.0",
46
- "@principles/host-runtime": "^4.2.0",
47
- "@principles/install-layout": "^0.8.1"
45
+ "@principles/core": "^7.10.1",
46
+ "@principles/host-runtime": "^4.4.0",
47
+ "@principles/install-layout": "^0.8.3"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@types/node": "^26.6.6",
@@ -61,5 +61,5 @@
61
61
  "publishConfig": {
62
62
  "access": "public"
63
63
  },
64
- "gitHead": "7feb0044cae3768b8bf278dad1cb58e77410b6f9"
64
+ "gitHead": "57948395d8f4c8763027b95dd3e9463cba846bce"
65
65
  }
@@ -84,6 +84,7 @@ const INITIAL_ENV_PRESENCE = Object.freeze({
84
84
  const logState = {
85
85
  host: 'unknown',
86
86
  bindingPathExists: false,
87
+ bindingSource: 'not_checked',
87
88
  workspaceResolution: 'not_checked',
88
89
  seq: 0,
89
90
  runId: null,
@@ -354,6 +355,86 @@ function isInside(parent, child) {
354
355
  return relative !== '' && relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
355
356
  }
356
357
 
358
+ // PRI-1247: a binding must never point one host at ANOTHER host's owned default
359
+ // governance workspace (the Codex installer used to inherit the OpenClaw
360
+ // detection result). This mirrors `findForeignWorkspaceHost` in
361
+ // @principles/install-layout; the parity test pins both sides together.
362
+ function hostOwnedWorkspaces(bindingHost, homeDir, codexHome) {
363
+ switch (bindingHost) {
364
+ case 'openclaw':
365
+ return [path.join(homeDir, 'clawd'), path.join(homeDir, '.openclaw', 'workspace')];
366
+ case 'codex':
367
+ return [path.join(codexHome, 'pd-workspace')];
368
+ case 'workbuddy':
369
+ return [path.join(homeDir, '.workbuddy', 'pd-workspace')];
370
+ default:
371
+ return [];
372
+ }
373
+ }
374
+
375
+ function findForeignWorkspaceOwner(bindingHost, workspaceDir, homeDir, codexHome) {
376
+ const normalize = (value) => {
377
+ const resolved = path.resolve(value);
378
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
379
+ };
380
+ const target = normalize(workspaceDir);
381
+ for (const other of KNOWN_HOSTS) {
382
+ if (other === bindingHost) continue;
383
+ for (const owned of hostOwnedWorkspaces(other, homeDir, codexHome)) {
384
+ if (isInsideOrSame(normalize(owned), target)) return other;
385
+ }
386
+ }
387
+ return null;
388
+ }
389
+
390
+ /**
391
+ * Derive the Codex home from this launcher's own payload path:
392
+ * `<codexHome>/plugins/cache/<marketplace>/principles-disciple/<version>`.
393
+ * Returns null for any other layout (tests, OpenClaw/WorkBuddy payloads), so
394
+ * the persistent-binding lookup is inert where it does not apply.
395
+ */
396
+ function deriveCodexHomeFromPayload(root) {
397
+ const pluginDir = path.dirname(root);
398
+ const marketplaceDir = path.dirname(pluginDir);
399
+ const cacheDir = path.dirname(marketplaceDir);
400
+ const pluginsDir = path.dirname(cacheDir);
401
+ if (path.basename(pluginDir) !== 'principles-disciple') return null;
402
+ if (path.basename(cacheDir) !== 'cache' || path.basename(pluginsDir) !== 'plugins') return null;
403
+ const home = path.dirname(pluginsDir);
404
+ return path.isAbsolute(home) ? home : null;
405
+ }
406
+
407
+ /**
408
+ * PRI-1248: host-persistent binding candidates, in authority order. A Codex
409
+ * cache refresh deletes anything inside the versioned payload, so the copy in
410
+ * PLUGIN_DATA must be authoritative; the payload-local file stays as the
411
+ * legacy fallback for bindings written before this change.
412
+ */
413
+ function codexPersistentBindingCandidates(root) {
414
+ const candidates = [];
415
+ const pluginData = typeof process.env.PLUGIN_DATA === 'string' ? process.env.PLUGIN_DATA.trim() : '';
416
+ if (pluginData.length > 0 && path.isAbsolute(pluginData)) {
417
+ candidates.push(path.join(path.resolve(pluginData), 'mcp-binding.json'));
418
+ }
419
+ const codexHome = deriveCodexHomeFromPayload(root);
420
+ if (codexHome !== null) {
421
+ const marketplace = path.basename(path.dirname(path.dirname(root)));
422
+ const dataRoot = path.join(codexHome, 'plugins', 'data');
423
+ let matches = [];
424
+ try {
425
+ matches = fs.readdirSync(dataRoot).filter((name) => name.startsWith('principles-disciple-'));
426
+ } catch {
427
+ // First run before PLUGIN_DATA exists: fall through to the canonical name.
428
+ }
429
+ if (matches.length === 1) {
430
+ candidates.push(path.join(dataRoot, matches[0], 'mcp-binding.json'));
431
+ } else if (/^[A-Za-z0-9._-]+$/.test(marketplace)) {
432
+ candidates.push(path.join(dataRoot, `principles-disciple-${marketplace}`, 'mcp-binding.json'));
433
+ }
434
+ }
435
+ return [...new Set(candidates)];
436
+ }
437
+
357
438
  const PD_CONFIG_FILENAME = 'principles-disciple.json';
358
439
 
359
440
  /** A declared workspace must be one fixed, real directory — never HOME or a drive root. */
@@ -448,11 +529,35 @@ logState.host = host;
448
529
 
449
530
  // rc-1/rc-3/rc-5: the binding file is read as untrusted; every field is
450
531
  // validated before use and unknown content is never coerced.
451
- const bindingPath = path.join(pluginRoot, 'mcp-binding.json');
452
- try {
453
- logState.bindingPathExists = fs.statSync(bindingPath).isFile();
454
- } catch {
455
- logState.bindingPathExists = false;
532
+ // PRI-1248: a Codex payload directory is replaceable, so the host-persistent
533
+ // copy in PLUGIN_DATA is authoritative; the payload-local file remains the
534
+ // legacy fallback for bindings written before the durable location existed.
535
+ const legacyBindingPath = path.join(pluginRoot, 'mcp-binding.json');
536
+ const bindingCandidates = host === 'codex'
537
+ ? [...codexPersistentBindingCandidates(pluginRoot), legacyBindingPath]
538
+ : [legacyBindingPath];
539
+ let bindingPath = null;
540
+ for (const candidate of bindingCandidates) {
541
+ try {
542
+ if (fs.statSync(candidate).isFile()) {
543
+ bindingPath = candidate;
544
+ break;
545
+ }
546
+ } catch {
547
+ // Absent candidate — try the next location.
548
+ }
549
+ }
550
+ logState.bindingPathExists = bindingPath !== null;
551
+ logState.bindingSource = bindingPath === null
552
+ ? 'missing'
553
+ : (bindingPath === legacyBindingPath ? 'payload' : 'persistent');
554
+ if (bindingPath === null) {
555
+ fail(
556
+ 'binding_missing',
557
+ host === 'codex'
558
+ ? `Re-run the PD host setup (Codex: $pd-control setup) so mcp-binding.json is written for this host (checked ${bindingCandidates.join(' and ')}).`
559
+ : 'Re-run the PD host setup (Codex: $pd-control setup) so mcp-binding.json is written into the plugin directory.',
560
+ );
456
561
  }
457
562
  let raw;
458
563
  try {
@@ -568,6 +673,27 @@ if (!workspaceStat.isDirectory()) {
568
673
  }
569
674
  logState.workspaceResolution = 'ok';
570
675
 
676
+ // PRI-1247: "exists and is a directory" is not ownership. A binding left by
677
+ // the old OpenClaw-oriented detection points Codex at OpenClaw's governance
678
+ // tree, so pain evidence would land in the wrong database. Refuse that before
679
+ // any MCP traffic; the OpenClaw declaration gate below is unchanged.
680
+ // The payload-derived Codex home is only meaningful when THIS payload is a
681
+ // Codex payload: WorkBuddy/OpenClaw caches share the same
682
+ // `<root>/plugins/cache/<marketplace>/principles-disciple/<version>` shape, and
683
+ // deriving from them would invent a Codex workspace inside the host's own tree.
684
+ const ownershipHome = os.homedir();
685
+ const ownershipCodexHome = (host === 'codex' ? deriveCodexHomeFromPayload(pluginRoot) : null)
686
+ ?? (typeof process.env.CODEX_HOME === 'string' && path.isAbsolute(process.env.CODEX_HOME)
687
+ ? path.resolve(process.env.CODEX_HOME)
688
+ : path.join(ownershipHome, '.codex'));
689
+ const foreignWorkspaceHost = findForeignWorkspaceOwner(host, binding.workspaceDir, ownershipHome, ownershipCodexHome);
690
+ if (foreignWorkspaceHost !== null) {
691
+ fail(
692
+ `binding_workspace_foreign_host:${foreignWorkspaceHost}`,
693
+ `mcp-binding.json binds ${foreignWorkspaceHost}'s default governance workspace. Re-run the PD host setup for ${host} with ITS OWN workspace (or an explicit supported --workspace), so pain evidence is not written into another host's database.`,
694
+ );
695
+ }
696
+
571
697
  // P0 (2026-11-13): an experiment must never bind a workspace outside its own
572
698
  // root. The binding is untrusted input written by another process generation;
573
699
  // a stale one (or one produced from an inherited production pointer) keeps the
@@ -622,6 +748,7 @@ writeLogEvent('info', 'launcher_start', {
622
748
  launcherVersion: LAUNCHER_VERSION,
623
749
  mcpServerVersion: packageManifest.version,
624
750
  bindingPathExists: logState.bindingPathExists,
751
+ bindingSource: logState.bindingSource,
625
752
  workspaceResolution: logState.workspaceResolution,
626
753
  envPresence: INITIAL_ENV_PRESENCE,
627
754
  });