@principles/workbuddy-adapter 0.7.0 → 0.8.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.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/worker/workspace-worker.d.ts +7 -0
- package/dist/worker/workspace-worker.js +182 -10
- package/package.json +5 -5
- package/plugin/.codebuddy-plugin/plugin.json +2 -2
- package/plugin/mcp/launcher.cjs +40 -4
- package/plugin/skills/pd-pain-signal/SKILL.md +10 -2
package/dist/index.d.ts
CHANGED
|
@@ -13,5 +13,5 @@ export { resolveWorkbuddyWorkspace, type WorkbuddyWorkspaceResolution, } from '.
|
|
|
13
13
|
export { WORKBUDDY_TOOL_SEMANTICS, WORKBUDDY_TOOL_SEMANTIC_MAPPINGS, } from './tool-semantics.js';
|
|
14
14
|
export { recordWorkbuddyPromptDeliveryEvidence, recordWorkbuddyDenyEvidence, workbuddyCapabilityDeclarations, WORKBUDDY_EVIDENCE_ADAPTER_VERSION, } from './workbuddy-evidence-recorder.js';
|
|
15
15
|
export { processWorkbuddyHookInvocation, annotateContextWarnings, type WorkBuddyPdHookResult, } from './pd-hook.js';
|
|
16
|
-
export { runWorkbuddyWorkspaceWorkerCycle, type WorkbuddyWorkerCycleResult, type WorkbuddyWorkerCycleOptions, type WorkbuddyWorkerCycleStepReport, type WorkbuddyWorkerMode, } from './worker/workspace-worker.js';
|
|
16
|
+
export { runWorkbuddyWorkspaceWorkerCycle, readWorkbuddyWorkerLiveness, workbuddyWorkerCycleDriver, type WorkbuddyWorkerCycleResult, type WorkbuddyWorkerCycleOptions, type WorkbuddyWorkerCycleStepReport, type WorkbuddyWorkerMode, } from './worker/workspace-worker.js';
|
|
17
17
|
export { encodeWorkbuddyCwd, deriveWorkbuddyTranscriptPath, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot, resolveWorkbuddyProjectsRoot, decodeWorkbuddyTranscriptWindow, createWorkbuddyTranscriptSource, WORKBUDDY_SINGLE_SESSION_ALERT_BYTES, type WorkbuddyTranscriptFileIdentity, type WorkbuddyTranscriptPathValidation, type DecodedWorkbuddyDelta, type DecodeWorkbuddyWindowInput, type WorkbuddyTranscriptSourceContext, ingestWorkbuddyConversation, workbuddyIngestionHints, catchUpWorkbuddyIngestion, locateWorkbuddyTranscriptBySessionIdentity, type WorkbuddyIngestionOptions, type WorkbuddyIngestionOutcome, type WorkbuddyCatchUpOptions, type WorkbuddyCatchUpResult, } from './ingestion/index.js';
|
package/dist/index.js
CHANGED
|
@@ -13,5 +13,5 @@ export { resolveWorkbuddyWorkspace, } from './workspace-resolution.js';
|
|
|
13
13
|
export { WORKBUDDY_TOOL_SEMANTICS, WORKBUDDY_TOOL_SEMANTIC_MAPPINGS, } from './tool-semantics.js';
|
|
14
14
|
export { recordWorkbuddyPromptDeliveryEvidence, recordWorkbuddyDenyEvidence, workbuddyCapabilityDeclarations, WORKBUDDY_EVIDENCE_ADAPTER_VERSION, } from './workbuddy-evidence-recorder.js';
|
|
15
15
|
export { processWorkbuddyHookInvocation, annotateContextWarnings, } from './pd-hook.js';
|
|
16
|
-
export { runWorkbuddyWorkspaceWorkerCycle, } from './worker/workspace-worker.js';
|
|
16
|
+
export { runWorkbuddyWorkspaceWorkerCycle, readWorkbuddyWorkerLiveness, workbuddyWorkerCycleDriver, } from './worker/workspace-worker.js';
|
|
17
17
|
export { encodeWorkbuddyCwd, deriveWorkbuddyTranscriptPath, validateWorkbuddyTranscriptPath, workbuddyProjectsRoot, resolveWorkbuddyProjectsRoot, decodeWorkbuddyTranscriptWindow, createWorkbuddyTranscriptSource, WORKBUDDY_SINGLE_SESSION_ALERT_BYTES, ingestWorkbuddyConversation, workbuddyIngestionHints, catchUpWorkbuddyIngestion, locateWorkbuddyTranscriptBySessionIdentity, } from './ingestion/index.js';
|
|
@@ -41,6 +41,13 @@ export interface WorkbuddyWorkerCycleOptions {
|
|
|
41
41
|
readonly stage2Classifier?: SignalLlmClassifier | null;
|
|
42
42
|
readonly stage2AggregateBudgetMs?: number;
|
|
43
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* WHO drove this cycle — same attribution contract as the Codex worker
|
|
46
|
+
* (PRI-1264 + Phase 2 `service_host` driver identity, TD §5.2).
|
|
47
|
+
*/
|
|
48
|
+
export declare function workbuddyWorkerCycleDriver(): 'companion' | 'service_host' | 'manual';
|
|
49
|
+
/** Read the persisted liveness record, or null when absent/unreadable. */
|
|
50
|
+
export declare function readWorkbuddyWorkerLiveness(workspaceDir: string): Record<string, unknown> | null;
|
|
44
51
|
/**
|
|
45
52
|
* Run ONE bounded worker cycle for a canonical governance workspace. Never
|
|
46
53
|
* throws: every failure becomes a structured degraded result with a
|
|
@@ -32,11 +32,62 @@
|
|
|
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, createGovernanceTrajectoryTurnReader, createHostIntentDocReader, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
|
|
35
|
+
import { loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, createGovernanceTrajectoryTurnReader, createConsentLedgerSourceMaterialAuthorization, createHostIntentDocReader, isAutomaticPainSubmissionAuthorized, 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';
|
|
39
39
|
const DEFAULT_DIAG_CANDIDATE_LIMIT = 5;
|
|
40
|
+
// ── Cycle liveness (Phase 2, SPEC §11 / TD §2.3: WorkBuddy had NO liveness
|
|
41
|
+
// record — FR-10 health was undecidable). Same shape and atomic-write
|
|
42
|
+
// discipline as the Codex worker's `.state/codex-worker-liveness.json`
|
|
43
|
+
// (CR-08 §9.3: liveness facts are worker-owned runtime state, never
|
|
44
|
+
// governance truth). ────────────────────────────────────────────────────
|
|
45
|
+
const LIVENESS_FILE = 'workbuddy-worker-liveness.json';
|
|
46
|
+
const LIVENESS_STAGE_DEADLINE_MS = {
|
|
47
|
+
catch_up: 5 * 60_000,
|
|
48
|
+
reconcile: 5 * 60_000,
|
|
49
|
+
diagnosis_execution: 15 * 60_000,
|
|
50
|
+
downstream_cycle: 10 * 60_000,
|
|
51
|
+
};
|
|
52
|
+
function isPlainRecord(value) {
|
|
53
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* WHO drove this cycle — same attribution contract as the Codex worker
|
|
57
|
+
* (PRI-1264 + Phase 2 `service_host` driver identity, TD §5.2).
|
|
58
|
+
*/
|
|
59
|
+
export function workbuddyWorkerCycleDriver() {
|
|
60
|
+
const source = process.env.PD_INVOCATION_SOURCE;
|
|
61
|
+
if (source === 'companion')
|
|
62
|
+
return 'companion';
|
|
63
|
+
if (source === 'service_host')
|
|
64
|
+
return 'service_host';
|
|
65
|
+
return 'manual';
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* F13 (TD §5.2): the coordinator passes a unique invocation id; when
|
|
69
|
+
* present it lands in the liveness record so the shared per-workspace file
|
|
70
|
+
* can be correlated back to the exact Service Host invocation.
|
|
71
|
+
* R5 review fix: a manual/companion cycle carries NO invocation id, so the
|
|
72
|
+
* patch must CLEAR the field — otherwise a completed manual run would keep
|
|
73
|
+
* masquerading under the previous shadow run's id.
|
|
74
|
+
*/
|
|
75
|
+
function invocationIdLivenessPatch() {
|
|
76
|
+
const invocationId = process.env.PD_INVOCATION_ID;
|
|
77
|
+
return typeof invocationId === 'string' && invocationId.length > 0
|
|
78
|
+
? { lastInvocationId: invocationId }
|
|
79
|
+
: { lastInvocationId: null };
|
|
80
|
+
}
|
|
81
|
+
/** Read the persisted liveness record, or null when absent/unreadable. */
|
|
82
|
+
export function readWorkbuddyWorkerLiveness(workspaceDir) {
|
|
83
|
+
try {
|
|
84
|
+
const parsed = JSON.parse(fs.readFileSync(path.join(path.resolve(workspaceDir), '.state', LIVENESS_FILE), 'utf8'));
|
|
85
|
+
return isPlainRecord(parsed) ? parsed : null;
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
40
91
|
function workerLogger(logger) {
|
|
41
92
|
return logger ?? {
|
|
42
93
|
info: () => undefined,
|
|
@@ -52,6 +103,59 @@ function directoryExists(dir) {
|
|
|
52
103
|
return false;
|
|
53
104
|
}
|
|
54
105
|
}
|
|
106
|
+
function writeLiveness(workspaceDir, patch) {
|
|
107
|
+
try {
|
|
108
|
+
const root = path.resolve(workspaceDir);
|
|
109
|
+
const stateDir = path.join(root, '.state');
|
|
110
|
+
const file = path.join(stateDir, LIVENESS_FILE);
|
|
111
|
+
if (!file.startsWith(root + path.sep))
|
|
112
|
+
return;
|
|
113
|
+
if (!directoryExists(stateDir))
|
|
114
|
+
fs.mkdirSync(stateDir, { recursive: true });
|
|
115
|
+
let current = {};
|
|
116
|
+
try {
|
|
117
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
118
|
+
if (isPlainRecord(parsed))
|
|
119
|
+
current = parsed;
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
current = {};
|
|
123
|
+
}
|
|
124
|
+
const merged = { ...current, ...patch, updatedAt: new Date().toISOString() };
|
|
125
|
+
// Exclusive random temp + rename (same CodeQL-safe pattern as Codex).
|
|
126
|
+
const tmp = path.join(stateDir, `${LIVENESS_FILE}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 10)}.tmp`);
|
|
127
|
+
const fd = fs.openSync(tmp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
|
|
128
|
+
try {
|
|
129
|
+
fs.writeFileSync(fd, JSON.stringify(merged));
|
|
130
|
+
}
|
|
131
|
+
finally {
|
|
132
|
+
fs.closeSync(fd);
|
|
133
|
+
}
|
|
134
|
+
fs.renameSync(tmp, file);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
// Liveness bookkeeping must never break the cycle (rc-9: the cycle
|
|
138
|
+
// report remains the observable degradation channel).
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* F9 review fix: settle the liveness record for EARLY returns (consumer
|
|
143
|
+
* pause, structured degradations). A cycle that stops after the `catch_up`
|
|
144
|
+
* stage write must not leave a stale runningStage + deadline behind —
|
|
145
|
+
* liveness readers would report the finished cycle as still mid-stage.
|
|
146
|
+
*/
|
|
147
|
+
function finalizeLiveness(workspaceDir, cycleStartedAt, settlement) {
|
|
148
|
+
writeLiveness(workspaceDir, {
|
|
149
|
+
runningStage: null,
|
|
150
|
+
stageDeadline: null,
|
|
151
|
+
lastCycleCompletedAt: new Date().toISOString(),
|
|
152
|
+
lastCycleDurationMs: Date.now() - cycleStartedAt.getTime(),
|
|
153
|
+
lastCycleMode: settlement.mode,
|
|
154
|
+
lastCycleDriver: workbuddyWorkerCycleDriver(),
|
|
155
|
+
...(settlement.reason !== undefined ? { lastDegradedReason: settlement.reason } : {}),
|
|
156
|
+
...invocationIdLivenessPatch(),
|
|
157
|
+
});
|
|
158
|
+
}
|
|
55
159
|
/**
|
|
56
160
|
* Oldest pending diagnostician first; retry_wait candidates are filtered to
|
|
57
161
|
* those whose backoff window has ELAPSED (same discipline as the Codex
|
|
@@ -80,6 +184,7 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
|
|
|
80
184
|
const logger = workerLogger(options.logger);
|
|
81
185
|
const emitEvent = options.emitEvent ?? ((_event, _payload) => undefined);
|
|
82
186
|
const base = { workspaceDir };
|
|
187
|
+
const cycleStartedAt = new Date();
|
|
83
188
|
// Step 1 — Workspace eligibility.
|
|
84
189
|
if (!directoryExists(workspaceDir)) {
|
|
85
190
|
return { ...base, mode: 'degraded', reason: 'workspace_missing', nextAction: 'The governance workspace directory no longer exists; run the WorkBuddy setup flow to re-initialize it. No PD state was mutated.' };
|
|
@@ -91,9 +196,25 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
|
|
|
91
196
|
}
|
|
92
197
|
const { flags } = computeFeatureFlagsFromConfig(config.effective);
|
|
93
198
|
if (flags['host.workbuddy']?.enabled !== true) {
|
|
199
|
+
// Same PRI-1264 discipline as Codex: an intentional CONFIG pause keeps
|
|
200
|
+
// the heartbeat alive — the worker IS cycling, deliberately idle.
|
|
201
|
+
writeLiveness(workspaceDir, {
|
|
202
|
+
runningStage: 'paused',
|
|
203
|
+
stageDeadline: null,
|
|
204
|
+
lastCycleStartedAt: cycleStartedAt.toISOString(),
|
|
205
|
+
lastCycleDriver: workbuddyWorkerCycleDriver(),
|
|
206
|
+
});
|
|
94
207
|
// PRI-1063 (review fix): single-line flow mapping — see pd-hook.ts.
|
|
95
208
|
return { ...base, mode: 'paused', reason: 'host.workbuddy_disabled', nextAction: 'Enable WorkBuddy PD behavior in the governance workspace .pd/config.yaml — in the existing "features:" block set host.workbuddy: {enabled: true} (one flat key, not nested).' };
|
|
96
209
|
}
|
|
210
|
+
// Liveness bookkeeping starts only after eligibility (CR-08 ordering —
|
|
211
|
+
// writing into a missing workspace directory would fabricate it).
|
|
212
|
+
writeLiveness(workspaceDir, {
|
|
213
|
+
lastCycleStartedAt: cycleStartedAt.toISOString(),
|
|
214
|
+
runningStage: 'catch_up',
|
|
215
|
+
stageDeadline: new Date(cycleStartedAt.getTime() + LIVENESS_STAGE_DEADLINE_MS.catch_up).toISOString(),
|
|
216
|
+
lastCycleDriver: workbuddyWorkerCycleDriver(),
|
|
217
|
+
});
|
|
97
218
|
const consumerFlag = loadFeatureFlagFromConfig(workspaceDir, 'internalization_auto_consumer', { info: (m) => logger.info(m), warn: (m) => logger.warn(m) });
|
|
98
219
|
// The Diagnostician capability gate resolves from the same canonical
|
|
99
220
|
// authority as the runtime factory. An Owner-disabled agent is an
|
|
@@ -133,17 +254,46 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
|
|
|
133
254
|
};
|
|
134
255
|
}
|
|
135
256
|
else if (!consumerFlag.enabled) {
|
|
257
|
+
// F9: the cycle ENDED here (paused) — settle the liveness record so the
|
|
258
|
+
// in-flight `catch_up` stage and its deadline do not survive it.
|
|
259
|
+
// P2-01 (final-remediation review): EVERY earlier stage's failure must
|
|
260
|
+
// reach the result — not catch-up only. A reconcile failure under a
|
|
261
|
+
// consumer pause is a degraded cycle, never a clean paused + exit 0.
|
|
262
|
+
const prePauseDegradations = [];
|
|
263
|
+
if (catchUp.status === 'degraded') {
|
|
264
|
+
prePauseDegradations.push(`catch_up:${catchUp.reason ?? 'degraded'}`);
|
|
265
|
+
}
|
|
266
|
+
if (!reconcile.ok) {
|
|
267
|
+
prePauseDegradations.push(`reconcile:${reconcile.reason ?? 'failed'}`);
|
|
268
|
+
}
|
|
269
|
+
for (const d of reconcile.degradations) {
|
|
270
|
+
const tagged = `reconcile:${d}`;
|
|
271
|
+
if (!prePauseDegradations.includes(tagged))
|
|
272
|
+
prePauseDegradations.push(tagged);
|
|
273
|
+
}
|
|
274
|
+
if (prePauseDegradations.length > 0) {
|
|
275
|
+
const reason = `paused_stage_failures:${prePauseDegradations.join('|').slice(0, 160)}`;
|
|
276
|
+
finalizeLiveness(workspaceDir, cycleStartedAt, { mode: 'degraded', reason });
|
|
277
|
+
return {
|
|
278
|
+
...base,
|
|
279
|
+
mode: 'degraded',
|
|
280
|
+
reason,
|
|
281
|
+
// Keep the REAL failing stage's recovery guidance ahead of the
|
|
282
|
+
// generic pause hint (P2-01 §C: catchUp.nextAction must not be
|
|
283
|
+
// overwritten by a generic paused suggestion).
|
|
284
|
+
nextAction: catchUp.status === 'degraded' && catchUp.nextAction !== undefined
|
|
285
|
+
? catchUp.nextAction
|
|
286
|
+
: (reconcile.nextAction ?? 'Inspect the governance workspace trajectory store and transcript consent; the worker retries automatically on the next cycle.'),
|
|
287
|
+
degradations: prePauseDegradations,
|
|
288
|
+
report: { catchUp, reconcile, diagnostician: null, downstream: null },
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
finalizeLiveness(workspaceDir, cycleStartedAt, { mode: 'paused' });
|
|
136
292
|
return {
|
|
137
293
|
...base,
|
|
138
294
|
mode: 'paused',
|
|
139
295
|
reason: 'internalization_auto_consumer_disabled',
|
|
140
296
|
nextAction: 'Automatic internalization execution is paused for this governance workspace; manual commands remain available: pd diagnose, pd runtime internalization run-once.',
|
|
141
|
-
// Catch-up ran BEFORE this early return. Keeping its degradation on the
|
|
142
|
-
// paused result means `pd workbuddy worker --once` can still report a
|
|
143
|
-
// broken transcript catch-up instead of exiting as a clean pause.
|
|
144
|
-
...(catchUp.status === 'degraded'
|
|
145
|
-
? { degradations: [`catch_up:${catchUp.reason ?? 'degraded'}`] }
|
|
146
|
-
: {}),
|
|
147
297
|
report: { catchUp, reconcile, diagnostician: null, downstream: null },
|
|
148
298
|
};
|
|
149
299
|
}
|
|
@@ -171,7 +321,12 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
|
|
|
171
321
|
intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig: config.effective }),
|
|
172
322
|
// PRI-1265: the worker's Stage A gets the bound session's ORIGINAL
|
|
173
323
|
// turns from the workspace's own consent-tiered governance store.
|
|
174
|
-
trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir }),
|
|
324
|
+
trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir) }),
|
|
325
|
+
// PRI-1283 R2: latest-consent gate consulted per assembly / model call.
|
|
326
|
+
sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir),
|
|
327
|
+
// SPEC §9.6: lazy probe — a revoked flag stops persisted
|
|
328
|
+
// automatic_hook tasks at the bridge's execution boundary.
|
|
329
|
+
isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
|
|
175
330
|
});
|
|
176
331
|
const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
|
|
177
332
|
diagnostician = {
|
|
@@ -195,10 +350,13 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
|
|
|
195
350
|
}
|
|
196
351
|
catch (error) {
|
|
197
352
|
const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
|
|
353
|
+
const reason = `diagnostician_execution_failed:${detail}`;
|
|
354
|
+
// F9: settle the liveness record on the degraded early return.
|
|
355
|
+
finalizeLiveness(workspaceDir, cycleStartedAt, { mode: 'degraded', reason });
|
|
198
356
|
return {
|
|
199
357
|
...base,
|
|
200
358
|
mode: 'degraded',
|
|
201
|
-
reason
|
|
359
|
+
reason,
|
|
202
360
|
nextAction: 'Inspect the governance workspace runtime profile and provider configuration; the task keeps its pending/retry state and no evidence was mutated.',
|
|
203
361
|
report: { catchUp, reconcile, diagnostician: null, downstream: null },
|
|
204
362
|
};
|
|
@@ -215,14 +373,18 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
|
|
|
215
373
|
});
|
|
216
374
|
if (!declared.ok) {
|
|
217
375
|
logger.warn?.(`[PD:WorkbuddyWorker] Failed to persist WorkBuddy tool declaration: ${declared.reason} — host-neutral consumers will not find it (rc-9)`);
|
|
376
|
+
const reason = `host_tool_declaration_persist_failed:${declared.reason}`;
|
|
377
|
+
// F9: settle the liveness record on the degraded early return.
|
|
378
|
+
finalizeLiveness(workspaceDir, cycleStartedAt, { mode: 'degraded', reason });
|
|
218
379
|
return {
|
|
219
380
|
...base,
|
|
220
381
|
mode: 'degraded',
|
|
221
|
-
reason
|
|
382
|
+
reason,
|
|
222
383
|
nextAction: 'Repair WorkBuddy host declaration persistence (.pd/host-tool-semantics/workbuddy.json) before running the downstream internalization cycle; the worker retries automatically on the next cycle.',
|
|
223
384
|
report: { catchUp, reconcile, diagnostician, downstream: null },
|
|
224
385
|
};
|
|
225
386
|
}
|
|
387
|
+
writeLiveness(workspaceDir, { runningStage: 'downstream_cycle', stageDeadline: new Date(Date.now() + LIVENESS_STAGE_DEADLINE_MS.downstream_cycle).toISOString() });
|
|
226
388
|
const downstream = await runInternalizationConsumerCycle(workspaceDir, {
|
|
227
389
|
owner: WORKER_OWNER,
|
|
228
390
|
logLabel: 'WorkbuddyWorker',
|
|
@@ -258,6 +420,16 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
|
|
|
258
420
|
: downstream.skipReason === 'runtime_config_error' || downstream.skipReason === 'cycle_error' || downstream.skipReason === 'config_malformed' ? `downstream:${downstream.skipReason}`
|
|
259
421
|
: !stage2.ok ? `stage2:${stage2.reason ?? 'failed'}`
|
|
260
422
|
: undefined;
|
|
423
|
+
writeLiveness(workspaceDir, {
|
|
424
|
+
runningStage: null,
|
|
425
|
+
stageDeadline: null,
|
|
426
|
+
lastCycleCompletedAt: new Date().toISOString(),
|
|
427
|
+
lastCycleDurationMs: Date.now() - cycleStartedAt.getTime(),
|
|
428
|
+
lastCycleMode: degradedReason !== undefined ? 'degraded' : 'ready',
|
|
429
|
+
lastCycleDriver: workbuddyWorkerCycleDriver(),
|
|
430
|
+
...(degradedReason !== undefined ? { lastDegradedReason: degradedReason } : {}),
|
|
431
|
+
...invocationIdLivenessPatch(),
|
|
432
|
+
});
|
|
261
433
|
return {
|
|
262
434
|
...base,
|
|
263
435
|
mode: degradedReason !== undefined ? 'degraded' : 'ready',
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@principles/workbuddy-adapter",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
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": "^8.
|
|
46
|
-
"@principles/host-runtime": "^4.
|
|
47
|
-
"@principles/install-layout": "^0.
|
|
45
|
+
"@principles/core": "^8.1.0",
|
|
46
|
+
"@principles/host-runtime": "^4.6.0",
|
|
47
|
+
"@principles/install-layout": "^0.10.0"
|
|
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": "
|
|
64
|
+
"gitHead": "5e3b8d53d46dfb3884966a006be3996c1dd34428"
|
|
65
65
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "principles-disciple",
|
|
3
3
|
"version": "0.2.2",
|
|
4
|
-
"description": "Principles Disciple — Owner-governed behavior internalization for AI agents (WorkBuddy host adapter, ADR-0020 third host). Three independent states: (1) the PD installer registers this plugin and records enablement in settings.json (enabledPlugins[key]) — an existing Owner true/false choice
|
|
5
|
-
"defaultEnabled":
|
|
4
|
+
"description": "Principles Disciple — Owner-governed behavior internalization for AI agents (WorkBuddy host adapter, ADR-0020 third host). Three independent states: (1) the PD installer registers this plugin and records enablement in settings.json (enabledPlugins[key]) — an existing Owner true/false choice always wins, otherwise the manifest defaultEnabled=true applies, so a fresh install is ENABLED out of the box and both its hooks and the bundled pd-recall MCP server load on the next session (the Owner can still disable it at any time); (2) governance is ON by default at install (features.host.workbuddy.enabled=true) and an explicit false opt-out is preserved; (3) automatic pain detection/correction is NOT available in WorkBuddy — record pain only with the explicit \"PD记录痛苦:\" prefix. Ships the read-only pd-recall MCP server (Gate 4).",
|
|
5
|
+
"defaultEnabled": true
|
|
6
6
|
}
|
package/plugin/mcp/launcher.cjs
CHANGED
|
@@ -435,6 +435,33 @@ function readAbsoluteWorkspaceField(parsed, field) {
|
|
|
435
435
|
* Comparison uses canonical directory identity so a junction, alias or case
|
|
436
436
|
* difference cannot smuggle one host's tree past another host's claim.
|
|
437
437
|
*/
|
|
438
|
+
/**
|
|
439
|
+
* Read the workspaceDir of another host's persisted payload binding, but only
|
|
440
|
+
* when the binding passes the SAME full shape validation the launcher applies
|
|
441
|
+
* to its own binding (schemaVersion, host marker, absolute workspaceDir/
|
|
442
|
+
* runtimeDir/serverEntry, semver versions.mcpServer, canonical server entry).
|
|
443
|
+
* A binding that would fail launch-time validation cannot form a workspace
|
|
444
|
+
* claim — fail-closed, mirroring `readWorkspaceFromBinding` in
|
|
445
|
+
* @principles/install-layout.
|
|
446
|
+
*/
|
|
447
|
+
function payloadBindingWorkspaceClaim(file, host) {
|
|
448
|
+
const parsed = readJson(file);
|
|
449
|
+
if (parsed === undefined) return undefined;
|
|
450
|
+
if (parsed.schemaVersion !== BINDING_SCHEMA) return undefined;
|
|
451
|
+
if (parsed.host !== host) return undefined;
|
|
452
|
+
if (typeof parsed.workspaceDir !== 'string' || !path.isAbsolute(parsed.workspaceDir.trim())) return undefined;
|
|
453
|
+
if (typeof parsed.runtimeDir !== 'string' || !path.isAbsolute(parsed.runtimeDir.trim())) return undefined;
|
|
454
|
+
if (typeof parsed.serverEntry !== 'string' || !path.isAbsolute(parsed.serverEntry.trim())) return undefined;
|
|
455
|
+
if (!isRecord(parsed.versions) || typeof parsed.versions.mcpServer !== 'string' || !SEMVER.test(parsed.versions.mcpServer)) return undefined;
|
|
456
|
+
// getCanonicalMcpServerEntry mirror: Codex uses the npm-dependency layout,
|
|
457
|
+
// the shared-runtime hosts the component layout.
|
|
458
|
+
const canonical = host === 'codex'
|
|
459
|
+
? path.join(parsed.runtimeDir, 'node_modules', '@principles', 'pd-mcp-server', 'dist', 'index.js')
|
|
460
|
+
: path.join(parsed.runtimeDir, 'pd-mcp-server', 'dist', 'index.js');
|
|
461
|
+
if (!samePath(parsed.serverEntry, canonical)) return undefined;
|
|
462
|
+
return path.resolve(parsed.workspaceDir.trim());
|
|
463
|
+
}
|
|
464
|
+
|
|
438
465
|
function hostDeclaredWorkspaceClaims(roots) {
|
|
439
466
|
const claims = [];
|
|
440
467
|
const declarationFiles = [
|
|
@@ -449,17 +476,26 @@ function hostDeclaredWorkspaceClaims(roots) {
|
|
|
449
476
|
const dataRoot = path.join(roots.codexHome, 'plugins', 'data');
|
|
450
477
|
for (const entry of fs.readdirSync(dataRoot)) {
|
|
451
478
|
if (typeof entry !== 'string' || !entry.startsWith('principles-disciple-')) continue;
|
|
452
|
-
const bound =
|
|
479
|
+
const bound = payloadBindingWorkspaceClaim(path.join(dataRoot, entry, 'mcp-binding.json'), 'codex');
|
|
453
480
|
if (bound !== undefined) claims.push({ host: 'codex', workspaceDir: bound });
|
|
454
481
|
}
|
|
455
482
|
} catch {
|
|
456
483
|
// No Codex plugin data on this machine — nothing to claim.
|
|
457
484
|
}
|
|
458
|
-
const wbBound =
|
|
459
|
-
|
|
460
|
-
'
|
|
485
|
+
const wbBound = payloadBindingWorkspaceClaim(
|
|
486
|
+
path.join(roots.homeDir, '.pd', 'workbuddy-marketplace', 'principles-disciple', 'mcp-binding.json'),
|
|
487
|
+
'workbuddy',
|
|
461
488
|
);
|
|
462
489
|
if (wbBound !== undefined) claims.push({ host: 'workbuddy', workspaceDir: wbBound });
|
|
490
|
+
// P0-1: the OpenClaw plugin persists its own binding beside its installed
|
|
491
|
+
// extension (<openclawHome>/extensions/principles-disciple/mcp-binding.json).
|
|
492
|
+
// Without this read, a non-default workspace OpenClaw bound via
|
|
493
|
+
// PD_WORKSPACE_DIR/OPENCLAW_WORKSPACE was invisible to ownership checks.
|
|
494
|
+
const ocBound = payloadBindingWorkspaceClaim(
|
|
495
|
+
path.join(roots.openclawHome, 'extensions', 'principles-disciple', 'mcp-binding.json'),
|
|
496
|
+
'openclaw',
|
|
497
|
+
);
|
|
498
|
+
if (ocBound !== undefined) claims.push({ host: 'openclaw', workspaceDir: ocBound });
|
|
463
499
|
return claims;
|
|
464
500
|
}
|
|
465
501
|
|
|
@@ -7,11 +7,17 @@ description: 记录一条"相对锚点的显著行为背离"(Pain)。Owner
|
|
|
7
7
|
|
|
8
8
|
# PD Pain Signal(WorkBuddy)
|
|
9
9
|
|
|
10
|
-
Pain
|
|
10
|
+
Pain 是定位和触发信号,不是数据集样本本体;样本单位是有完整上下文的行为偏差事件。必须在具体 Owner、任务和决策时点中,比较宿主行为与当时可证实的用户预期、意图及适用 PD 原则。任务成功仍可能偏离;任务失败也不自动意味着偏离。不得把“少询问、执行快、检查多”等行为风格当作普遍更好。
|
|
11
|
+
|
|
12
|
+
完整事件需要关联原始相关对话轨迹、工具调用与返回、产物和状态变化;摘要不能替代原始轨迹。区分当时宿主有机会获知的期望、事后澄清和评价者推断。完整归档可以包含后续纠正,但不得将后续信息泄漏给更早的决策点评测。完整轨迹暂不可用时,不要因此丢弃合法 Pain:按现有授权入口保存可验证信号与来源线索,明确保留为不完整候选,不得宣称完整样本,也不得绕过留存授权补齐。
|
|
13
|
+
|
|
14
|
+
规范详见 [PD 行为偏差事件与相对评价规范](https://github.com/csuzngjh/principles/blob/main/docs/concepts/PD_BEHAVIOR_DEVIATION_EVENT_AND_RELATIVE_EVALUATION.md)。当前提交接口仍要求一个主锚点;这是入口字段约束,不代表完整事件只包含一个期望依据。额外期望或原则冲突应在 reason 中如实保留。
|
|
15
|
+
|
|
16
|
+
当前提交接口的主锚点仍需满足以下要求:
|
|
11
17
|
|
|
12
18
|
1. **锚点** —— Owner 的明示要求、既有原则,或生效中的 Agent 指令 / Skill 要求。
|
|
13
19
|
2. **具体行为** —— 你实际做了什么、漏了什么。
|
|
14
|
-
3.
|
|
20
|
+
3. **具体可说明的背离** —— 相对该锚点可以说清楚的差距;影响大小、重复次数和情绪强度不是提交门槛。
|
|
15
21
|
|
|
16
22
|
没有证明影响、没有重复发生、Owner 之前没纠正过,都**不是**不提交的理由,只影响 Owner 的注意力排序。
|
|
17
23
|
|
|
@@ -76,6 +82,8 @@ Owner 说过 —— 本次对话、Owner 文档或已批准的决定。`anchorRe
|
|
|
76
82
|
|
|
77
83
|
## `reason` —— 六部分,按顺序
|
|
78
84
|
|
|
85
|
+
以下六部分描述当前提交入口需要表达的主锚点,不等于完整事件的数据模型。完整事件中的事后澄清和评价者推断必须分开保存,不能冒充 Owner 原话或宿主当时已知的要求;只有推断不足以满足当前有锚点提交约束时,可以保留为待核验材料,不得伪装成已验证偏差。
|
|
86
|
+
|
|
79
87
|
1. **锚点** —— 引用或指明(原则 id@version、指令 path#section、Owner 原话 + 出处)。
|
|
80
88
|
2. **锚点来源与引用等级** —— `verbatim` / `paraphrase` / `recollection` / `inference`。不得抬高等级。仅有 `recollection` 或 `inference` 时不够:先与 Owner 确认原话。
|
|
81
89
|
3. **观察到的行为** —— 具体动作、顺序、跳过的步骤、越界之处。不要写"质量不好"。
|