@adamchanadam/agent-handoff-kit 0.3.40 โ 0.3.42
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/README.md +34 -34
- package/bin/agent-handoff-kit.mjs +4663 -2366
- package/bin/installed-file-contract.mjs +74 -0
- package/bin/migration-baselines/official-origin-catalog.json +10039 -0
- package/bin/official-origin-catalog.mjs +248 -0
- package/bin/semantic-candidate.mjs +594 -0
- package/bin/upgrade-inventory.mjs +587 -0
- package/bin/user-rules-router.mjs +461 -0
- package/package.json +1 -1
- package/packs/closeout.md +15 -13
- package/packs/communication.md +8 -6
- package/packs/onboarding.md +1 -1
- package/runtime-core/AGENTS.core.md +8 -5
- package/runtime-core/PROJECT_INDEX.md +73 -73
- package/runtime-core/SESSION_HANDOFF.md +12 -6
- package/runtime-core/START_NEXT_SESSION_PROMPT.txt +1 -1
- package/runtime-core/USER_RULES.md +30 -0
- package/runtime-core/USER_RULES_ENTRY.md +7 -0
- package/bin/migration-baselines/v0.3.38/integrations.md +0 -235
- package/bin/migration-baselines/v0.3.38/onboarding.md +0 -201
- package/bin/migration-baselines/v0.3.38/safety.md +0 -46
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstat, readFile, realpath } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
export const USER_RULES_ROUTER_PATH = "dev/USER_RULES.md";
|
|
6
|
+
export const USER_RULES_CONTENT_ROOT = "dev/user_rules/";
|
|
7
|
+
|
|
8
|
+
export const FORMAL_USER_RULES_ENTRY_ANCHOR = "<!-- ack:user-rules-router:dev/USER_RULES.md -->";
|
|
9
|
+
export const USER_RULES_ACCEPTANCE_SCHEMA_VERSION = 2;
|
|
10
|
+
const formalEntryInstruction = "Before loading task packs, read `dev/USER_RULES.md`.";
|
|
11
|
+
const acceptanceAnchorPattern = /<!-- ack:user-rules-acceptance:sha256=([a-f0-9]{64}) -->/g;
|
|
12
|
+
const registryStart = "<!-- ack:user-rules-registry:start -->";
|
|
13
|
+
const registryEnd = "<!-- ack:user-rules-registry:end -->";
|
|
14
|
+
const stateStart = "<!-- ack:user-rules-state:start -->";
|
|
15
|
+
const stateEnd = "<!-- ack:user-rules-state:end -->";
|
|
16
|
+
const managedCoreStart = "<!-- BEGIN Agent Handoff Kit managed core -->";
|
|
17
|
+
const managedCoreEnd = "<!-- END Agent Handoff Kit managed core -->";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Reads the formal user-rule path: AGENTS.md -> USER_RULES.md -> accepted,
|
|
21
|
+
* registered dev/user_rules entries. It is read-only: every rule must match
|
|
22
|
+
* its accepted raw-byte witness before it is returned, and the helper grants
|
|
23
|
+
* no migration or activation authority.
|
|
24
|
+
*/
|
|
25
|
+
export async function readFormalUserRules({ root, allowActiveTransaction = false } = {}) {
|
|
26
|
+
if (typeof root !== "string" || !root.trim()) throw new Error("user-rules reader requires a project root");
|
|
27
|
+
const rootPath = path.resolve(root);
|
|
28
|
+
const rootStats = await lstat(rootPath).catch((error) => {
|
|
29
|
+
if (error?.code === "ENOENT") return null;
|
|
30
|
+
throw error;
|
|
31
|
+
});
|
|
32
|
+
if (!rootStats?.isDirectory() || rootStats.isSymbolicLink()) throw new Error("user-rules reader root must be a real directory");
|
|
33
|
+
const realRoot = await realpath(rootPath);
|
|
34
|
+
if (!allowActiveTransaction && await hasActiveUpgradeLock(rootPath)) {
|
|
35
|
+
throw new Error("user-rules activation is pending recovery; normal entry refuses to read a partial transaction state");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const agents = await readSafeFile(rootPath, realRoot, "AGENTS.md");
|
|
39
|
+
const agentsText = agents.bytes.toString("utf8");
|
|
40
|
+
const formalEntry = parseFormalUserRulesEntry(agentsText);
|
|
41
|
+
|
|
42
|
+
const router = await readSafeFile(rootPath, realRoot, USER_RULES_ROUTER_PATH);
|
|
43
|
+
const entries = parseUserRulesRegistry(router.bytes.toString("utf8"));
|
|
44
|
+
const state = parseUserRulesState(router.bytes.toString("utf8"));
|
|
45
|
+
const acceptedDigest = formalEntry.acceptanceDigest;
|
|
46
|
+
const actualDigest = userRulesAcceptanceDigest(entries, state);
|
|
47
|
+
if (acceptedDigest !== actualDigest) {
|
|
48
|
+
throw new Error("AGENTS.md user-rules acceptance digest does not match the ordered registry state");
|
|
49
|
+
}
|
|
50
|
+
if (state) assertCurrentKitState(agentsText, state);
|
|
51
|
+
const rules = [];
|
|
52
|
+
for (const entry of entries) {
|
|
53
|
+
const rule = await readSafeFile(rootPath, realRoot, entry.contentPath);
|
|
54
|
+
assertAcceptedBytes(entry, rule.bytes);
|
|
55
|
+
rules.push(Object.freeze({ ...entry, path: entry.contentPath, bytes: rule.bytes, sha256: sha256(rule.bytes) }));
|
|
56
|
+
}
|
|
57
|
+
return Object.freeze({
|
|
58
|
+
entryPath: "AGENTS.md",
|
|
59
|
+
routerPath: USER_RULES_ROUTER_PATH,
|
|
60
|
+
agentsSha256: sha256(agents.bytes),
|
|
61
|
+
routerSha256: sha256(router.bytes),
|
|
62
|
+
acceptanceDigest: actualDigest,
|
|
63
|
+
state,
|
|
64
|
+
rules: Object.freeze(rules)
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Hashes the canonical whole acceptance state. This binds the entry sequence
|
|
70
|
+
* and every accepted witness / reader / priority / effect field to the formal
|
|
71
|
+
* AGENTS.md entry, so a partial router edit cannot silently change priority or
|
|
72
|
+
* meaning while retaining individually valid rule bytes.
|
|
73
|
+
*/
|
|
74
|
+
export function userRulesAcceptanceDigest(entries, state = null) {
|
|
75
|
+
if (!Array.isArray(entries)) throw new Error("user-rules acceptance digest requires an entry array");
|
|
76
|
+
const canonicalEntries = entries.map((entry, index) => normalizeUserRuleEntry(entry, index));
|
|
77
|
+
const canonical = state
|
|
78
|
+
? { schemaVersion: USER_RULES_ACCEPTANCE_SCHEMA_VERSION, state: normalizeUserRulesState(state), entries: canonicalEntries }
|
|
79
|
+
: { schemaVersion: 1, entries: canonicalEntries };
|
|
80
|
+
return sha256(`${JSON.stringify(canonical)}\n`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Creates the state portion of a whole acceptance witness. The Kit base is
|
|
85
|
+
* identified by its package version and the exact normalized managed-core
|
|
86
|
+
* bytes; user rules remain represented separately by their raw-byte entries.
|
|
87
|
+
*/
|
|
88
|
+
export function createUserRulesState({ packageVersion, agentsText } = {}) {
|
|
89
|
+
if (typeof packageVersion !== "string" || !/^\d+\.\d+\.\d+$/.test(packageVersion)) {
|
|
90
|
+
throw new Error("user-rules state requires a stable package version");
|
|
91
|
+
}
|
|
92
|
+
return Object.freeze({
|
|
93
|
+
kitBase: Object.freeze({
|
|
94
|
+
target: "AGENTS.md",
|
|
95
|
+
packageVersion,
|
|
96
|
+
managedCoreSha256: managedCoreSha256(agentsText)
|
|
97
|
+
}),
|
|
98
|
+
router: Object.freeze({
|
|
99
|
+
path: USER_RULES_ROUTER_PATH,
|
|
100
|
+
contentRoot: USER_RULES_CONTENT_ROOT
|
|
101
|
+
})
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Rewrites only the state and registry regions of the formal router. */
|
|
106
|
+
export function renderUserRulesRouter(routerText, { state, entries } = {}) {
|
|
107
|
+
const normalizedState = normalizeUserRulesState(state);
|
|
108
|
+
if (!Array.isArray(entries)) throw new Error("user-rules router rendering requires entries");
|
|
109
|
+
const canonicalEntries = entries.map((entry, index) => normalizeUserRuleEntry(entry, index));
|
|
110
|
+
const source = ensureStateRegion(String(routerText));
|
|
111
|
+
return replaceMarkedJson(
|
|
112
|
+
replaceMarkedJson(source, registryStart, registryEnd, canonicalEntries),
|
|
113
|
+
stateStart,
|
|
114
|
+
stateEnd,
|
|
115
|
+
normalizedState
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function ensureStateRegion(routerText) {
|
|
120
|
+
const hasStart = count(routerText, stateStart);
|
|
121
|
+
const hasEnd = count(routerText, stateEnd);
|
|
122
|
+
if (hasStart === 0 && hasEnd === 0) {
|
|
123
|
+
// A v1 formal router had no Kit-base state section. Adding this isolated,
|
|
124
|
+
// marker-bounded acceptance region leaves its registry and every user byte
|
|
125
|
+
// untouched; any malformed partial region is still rejected below.
|
|
126
|
+
return `${routerText.replace(/\s*$/, "")}\n\n${stateStart}\n\`\`\`json\n{}\n\`\`\`\n${stateEnd}\n`;
|
|
127
|
+
}
|
|
128
|
+
if (hasStart !== 1 || hasEnd !== 1) throw new Error("user-rules router state markers must be unique");
|
|
129
|
+
return routerText;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Replaces the sole formal acceptance digest in the AGENTS external entry. */
|
|
133
|
+
export function renderUserRulesAcceptanceDigest(agentsText, digest) {
|
|
134
|
+
if (typeof digest !== "string" || !/^[a-f0-9]{64}$/.test(digest)) throw new Error("user-rules acceptance digest is invalid");
|
|
135
|
+
const source = String(agentsText);
|
|
136
|
+
const entry = parseFormalUserRulesEntry(source);
|
|
137
|
+
const newline = source.includes("\r\n") ? "\r\n" : "\n";
|
|
138
|
+
const lines = source.split(/\r?\n/);
|
|
139
|
+
lines[entry.acceptanceDigestLine] = `<!-- ack:user-rules-acceptance:sha256=${digest} -->`;
|
|
140
|
+
return lines.join(newline);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Creates one canonical, hash-bound registration for a fresh user rule.
|
|
145
|
+
* Later migration code may supply a distinct source witness, but it must use
|
|
146
|
+
* the same strict schema and be accepted atomically with its target state.
|
|
147
|
+
*/
|
|
148
|
+
export function createFreshUserRuleAcceptance({ entryId, contentPath, bytes, priorityRelation = "before-task-packs", effectDecision = "fresh-user-rule" } = {}) {
|
|
149
|
+
const normalizedId = normalizeEntryId(entryId);
|
|
150
|
+
const normalizedPath = normalizeUserRulePath(contentPath);
|
|
151
|
+
const content = toBuffer(bytes, "fresh user-rule acceptance requires raw bytes");
|
|
152
|
+
const witness = byteWitness(content);
|
|
153
|
+
return Object.freeze({
|
|
154
|
+
entryId: normalizedId,
|
|
155
|
+
contentPath: normalizedPath,
|
|
156
|
+
accepted: witness,
|
|
157
|
+
sourceWitness: witness,
|
|
158
|
+
originalReader: Object.freeze({ reader: "fresh-user-registration", via: "user-controlled-content" }),
|
|
159
|
+
activeReader: Object.freeze({ reader: "AGENTS.md", via: USER_RULES_ROUTER_PATH }),
|
|
160
|
+
priorityRelation: requiredText(priorityRelation, "user-rules priority relation is required"),
|
|
161
|
+
effectDecision: requiredText(effectDecision, "user-rules effect decision is required")
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** True only for the canonical content area used by a registered rule. */
|
|
166
|
+
export function isFormalUserRulesContentPath(value) {
|
|
167
|
+
try {
|
|
168
|
+
return normalizeUserRulePath(value) === value;
|
|
169
|
+
} catch {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Parses the JSON acceptance registry delimited by the durable router markers.
|
|
176
|
+
* Directory placement, titles, language, and file shape are never ownership
|
|
177
|
+
* evidence; only the registry's accepted byte witness governs this reader.
|
|
178
|
+
*/
|
|
179
|
+
export function parseUserRulesRegistry(text) {
|
|
180
|
+
const source = String(text);
|
|
181
|
+
if (count(source, registryStart) !== 1 || count(source, registryEnd) !== 1) {
|
|
182
|
+
throw new Error("user-rules registry markers must be unique");
|
|
183
|
+
}
|
|
184
|
+
const start = source.indexOf(registryStart) + registryStart.length;
|
|
185
|
+
const end = source.indexOf(registryEnd);
|
|
186
|
+
if (end < start) throw new Error("user-rules registry markers are out of order");
|
|
187
|
+
const body = source.slice(start, end).trim();
|
|
188
|
+
const fenced = /^```json\r?\n([\s\S]*?)\r?\n```$/.exec(body);
|
|
189
|
+
if (!fenced) throw new Error("user-rules registry must be one JSON fenced block");
|
|
190
|
+
let rawEntries;
|
|
191
|
+
try {
|
|
192
|
+
rawEntries = JSON.parse(fenced[1]);
|
|
193
|
+
} catch {
|
|
194
|
+
throw new Error("user-rules registry JSON is invalid");
|
|
195
|
+
}
|
|
196
|
+
if (!Array.isArray(rawEntries)) throw new Error("user-rules registry must be a JSON array");
|
|
197
|
+
const entryIds = new Set();
|
|
198
|
+
const contentPaths = new Set();
|
|
199
|
+
return Object.freeze(rawEntries.map((value, index) => {
|
|
200
|
+
const entry = normalizeUserRuleEntry(value, index);
|
|
201
|
+
if (entryIds.has(entry.entryId)) throw new Error(`user-rules registry duplicates entry id: ${entry.entryId}`);
|
|
202
|
+
if (contentPaths.has(entry.contentPath)) throw new Error(`user-rules registry duplicates entry path: ${entry.contentPath}`);
|
|
203
|
+
entryIds.add(entry.entryId);
|
|
204
|
+
contentPaths.add(entry.contentPath);
|
|
205
|
+
return entry;
|
|
206
|
+
}));
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function parseUserRulesState(text) {
|
|
210
|
+
const source = String(text);
|
|
211
|
+
if (count(source, stateStart) === 0 && count(source, stateEnd) === 0) return null;
|
|
212
|
+
return normalizeUserRulesState(parseMarkedJson(source, stateStart, stateEnd, "user-rules state"));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function parseUserRulesAcceptanceDigest(agentsText) {
|
|
216
|
+
return parseFormalUserRulesEntry(agentsText).acceptanceDigest;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function parseFormalUserRulesEntry(agentsText) {
|
|
220
|
+
const source = String(agentsText);
|
|
221
|
+
if (count(source, FORMAL_USER_RULES_ENTRY_ANCHOR) !== 1) {
|
|
222
|
+
throw new Error("AGENTS.md must contain one formal user-rules entry");
|
|
223
|
+
}
|
|
224
|
+
const rawDigestMatches = [...source.matchAll(acceptanceAnchorPattern)];
|
|
225
|
+
if (rawDigestMatches.length !== 1) throw new Error("AGENTS.md must contain one user-rules acceptance digest");
|
|
226
|
+
|
|
227
|
+
const lines = source.split(/\r?\n/);
|
|
228
|
+
let fence = null;
|
|
229
|
+
let comment = false;
|
|
230
|
+
const activeAnchors = [];
|
|
231
|
+
const activeDigests = [];
|
|
232
|
+
const activeInstructionLines = new Set();
|
|
233
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
234
|
+
const trimmed = lines[index].trim();
|
|
235
|
+
const fenceMarker = /^(?:```|~~~)/.exec(trimmed)?.[0] ?? null;
|
|
236
|
+
if (fence) {
|
|
237
|
+
if (fenceMarker === fence) fence = null;
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
if (fenceMarker) {
|
|
241
|
+
fence = fenceMarker;
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
if (comment) {
|
|
245
|
+
if (trimmed.includes("-->")) comment = false;
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
if (trimmed === FORMAL_USER_RULES_ENTRY_ANCHOR) {
|
|
249
|
+
activeAnchors.push(index);
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
const digest = /^<!-- ack:user-rules-acceptance:sha256=([a-f0-9]{64}) -->$/.exec(trimmed);
|
|
253
|
+
if (digest) {
|
|
254
|
+
activeDigests.push({ index, digest: digest[1] });
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
if (trimmed.startsWith("<!--")) {
|
|
258
|
+
if (!trimmed.includes("-->")) comment = true;
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
if (trimmed.startsWith(formalEntryInstruction)) activeInstructionLines.add(index);
|
|
262
|
+
}
|
|
263
|
+
if (fence || comment || activeAnchors.length !== 1 || activeDigests.length !== 1) {
|
|
264
|
+
throw new Error("AGENTS.md does not contain one active formal user-rules entry");
|
|
265
|
+
}
|
|
266
|
+
const anchorLine = activeAnchors[0];
|
|
267
|
+
const digest = activeDigests[0];
|
|
268
|
+
if (digest.index !== anchorLine + 1 || !activeInstructionLines.has(digest.index + 1)) {
|
|
269
|
+
throw new Error("AGENTS.md formal user-rules entry is not an active canonical instruction");
|
|
270
|
+
}
|
|
271
|
+
return Object.freeze({ acceptanceDigest: digest.digest, acceptanceDigestLine: digest.index });
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function normalizeUserRulesState(value) {
|
|
275
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("user-rules state must be an object");
|
|
276
|
+
const kitBase = value.kitBase;
|
|
277
|
+
const router = value.router;
|
|
278
|
+
if (!kitBase || typeof kitBase !== "object" || Array.isArray(kitBase)
|
|
279
|
+
|| kitBase.target !== "AGENTS.md"
|
|
280
|
+
|| typeof kitBase.packageVersion !== "string" || !/^\d+\.\d+\.\d+$/.test(kitBase.packageVersion)
|
|
281
|
+
|| typeof kitBase.managedCoreSha256 !== "string" || !/^[a-f0-9]{64}$/.test(kitBase.managedCoreSha256)) {
|
|
282
|
+
throw new Error("user-rules Kit base state is invalid");
|
|
283
|
+
}
|
|
284
|
+
if (!router || typeof router !== "object" || Array.isArray(router)
|
|
285
|
+
|| router.path !== USER_RULES_ROUTER_PATH || router.contentRoot !== USER_RULES_CONTENT_ROOT) {
|
|
286
|
+
throw new Error("user-rules router state is invalid");
|
|
287
|
+
}
|
|
288
|
+
return Object.freeze({
|
|
289
|
+
kitBase: Object.freeze({ target: "AGENTS.md", packageVersion: kitBase.packageVersion, managedCoreSha256: kitBase.managedCoreSha256 }),
|
|
290
|
+
router: Object.freeze({ path: USER_RULES_ROUTER_PATH, contentRoot: USER_RULES_CONTENT_ROOT })
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function assertCurrentKitState(agentsText, state) {
|
|
295
|
+
if (managedCoreSha256(agentsText) !== state.kitBase.managedCoreSha256) {
|
|
296
|
+
throw new Error("AGENTS.md managed core does not match the accepted current user-rules state");
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function managedCoreSha256(agentsText) {
|
|
301
|
+
const source = String(agentsText).replace(/\r\n?/g, "\n");
|
|
302
|
+
const start = source.indexOf(managedCoreStart);
|
|
303
|
+
const end = source.indexOf(managedCoreEnd);
|
|
304
|
+
if (start < 0 || end < 0 || end <= start || count(source, managedCoreStart) !== 1 || count(source, managedCoreEnd) !== 1) {
|
|
305
|
+
throw new Error("AGENTS.md has no unique managed core for user-rules state");
|
|
306
|
+
}
|
|
307
|
+
const contentStart = start + managedCoreStart.length;
|
|
308
|
+
return sha256(Buffer.from(source.slice(contentStart, end).replace(/^\n|\n$/g, ""), "utf8"));
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function replaceMarkedJson(text, startMarker, endMarker, value) {
|
|
312
|
+
const source = String(text);
|
|
313
|
+
if (count(source, startMarker) !== 1 || count(source, endMarker) !== 1) {
|
|
314
|
+
throw new Error("user-rules router markers must be unique");
|
|
315
|
+
}
|
|
316
|
+
const start = source.indexOf(startMarker) + startMarker.length;
|
|
317
|
+
const end = source.indexOf(endMarker);
|
|
318
|
+
if (end < start) throw new Error("user-rules router markers are out of order");
|
|
319
|
+
return `${source.slice(0, start)}\n\`\`\`json\n${JSON.stringify(value, null, 2)}\n\`\`\`\n${source.slice(end)}`;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function parseMarkedJson(source, startMarker, endMarker, label) {
|
|
323
|
+
if (count(source, startMarker) !== 1 || count(source, endMarker) !== 1) throw new Error(`${label} markers must be unique`);
|
|
324
|
+
const start = source.indexOf(startMarker) + startMarker.length;
|
|
325
|
+
const end = source.indexOf(endMarker);
|
|
326
|
+
if (end < start) throw new Error(`${label} markers are out of order`);
|
|
327
|
+
const body = source.slice(start, end).trim();
|
|
328
|
+
const fenced = /^```json\r?\n([\s\S]*?)\r?\n```$/.exec(body);
|
|
329
|
+
if (!fenced) throw new Error(`${label} must be one JSON fenced block`);
|
|
330
|
+
try { return JSON.parse(fenced[1]); } catch { throw new Error(`${label} JSON is invalid`); }
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
async function hasActiveUpgradeLock(rootPath) {
|
|
334
|
+
const lockPath = path.join(rootPath, "dev", "governance_migrations", ".upgrade.lock");
|
|
335
|
+
try {
|
|
336
|
+
return Boolean(await lstat(lockPath));
|
|
337
|
+
} catch (error) {
|
|
338
|
+
if (error?.code === "ENOENT") return false;
|
|
339
|
+
throw error;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function normalizeUserRuleEntry(value, index) {
|
|
344
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`user-rules registry entry ${index + 1} must be an object`);
|
|
345
|
+
const entryId = normalizeEntryId(value.entryId);
|
|
346
|
+
const contentPath = normalizeUserRulePath(value.contentPath);
|
|
347
|
+
const accepted = normalizeByteWitness(value.accepted, `user-rules accepted bytes are invalid: ${contentPath}`);
|
|
348
|
+
const sourceWitness = normalizeByteWitness(value.sourceWitness, `user-rules source witness is invalid: ${contentPath}`);
|
|
349
|
+
if (accepted.sha256 !== sourceWitness.sha256 || accepted.bytes !== sourceWitness.bytes || accepted.contentBase64 !== sourceWitness.contentBase64) {
|
|
350
|
+
throw new Error(`user-rules source witness does not exactly match accepted bytes: ${contentPath}`);
|
|
351
|
+
}
|
|
352
|
+
const originalReader = normalizeReader(value.originalReader, "user-rules original reader is invalid");
|
|
353
|
+
const activeReader = normalizeReader(value.activeReader, "user-rules active reader is invalid");
|
|
354
|
+
if (activeReader.reader !== "AGENTS.md" || activeReader.via !== USER_RULES_ROUTER_PATH) {
|
|
355
|
+
throw new Error(`user-rules active reader is not the formal entry: ${contentPath}`);
|
|
356
|
+
}
|
|
357
|
+
if (value.priorityRelation !== "before-task-packs") {
|
|
358
|
+
throw new Error(`user-rules priority relation is not effective through the formal entry: ${contentPath}`);
|
|
359
|
+
}
|
|
360
|
+
if (value.effectDecision !== "fresh-user-rule") {
|
|
361
|
+
throw new Error(`user-rules effect decision is not accepted through the formal entry: ${contentPath}`);
|
|
362
|
+
}
|
|
363
|
+
return Object.freeze({
|
|
364
|
+
entryId,
|
|
365
|
+
contentPath,
|
|
366
|
+
accepted,
|
|
367
|
+
sourceWitness,
|
|
368
|
+
originalReader,
|
|
369
|
+
activeReader,
|
|
370
|
+
priorityRelation: "before-task-packs",
|
|
371
|
+
effectDecision: "fresh-user-rule"
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function normalizeByteWitness(value, message) {
|
|
376
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(message);
|
|
377
|
+
const sha = requiredText(value.sha256, message);
|
|
378
|
+
if (!/^[a-f0-9]{64}$/.test(sha)) throw new Error(message);
|
|
379
|
+
if (!Number.isInteger(value.bytes) || value.bytes < 0) throw new Error(message);
|
|
380
|
+
const content = decodeBase64(value.contentBase64, message);
|
|
381
|
+
if (content.length !== value.bytes || sha256(content) !== sha) throw new Error(message);
|
|
382
|
+
return Object.freeze({ sha256: sha, bytes: value.bytes, contentBase64: value.contentBase64 });
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function normalizeReader(value, message) {
|
|
386
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(message);
|
|
387
|
+
return Object.freeze({ reader: requiredText(value.reader, message), via: requiredText(value.via, message) });
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function assertAcceptedBytes(entry, bytes) {
|
|
391
|
+
if (bytes.length !== entry.accepted.bytes || sha256(bytes) !== entry.accepted.sha256 || !bytes.equals(Buffer.from(entry.accepted.contentBase64, "base64"))) {
|
|
392
|
+
throw new Error(`user-rules bytes do not match accepted witness: ${entry.contentPath}`);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
async function readSafeFile(rootPath, realRoot, relative) {
|
|
397
|
+
const absolute = path.resolve(rootPath, relative);
|
|
398
|
+
if (!isInside(rootPath, absolute)) throw new Error(`user-rules path escapes the project root: ${relative}`);
|
|
399
|
+
const stats = await lstat(absolute).catch((error) => {
|
|
400
|
+
if (error?.code === "ENOENT") return null;
|
|
401
|
+
throw error;
|
|
402
|
+
});
|
|
403
|
+
if (!stats?.isFile() || stats.isSymbolicLink()) throw new Error(`user-rules file is missing or unsafe: ${relative}`);
|
|
404
|
+
const resolved = await realpath(absolute);
|
|
405
|
+
if (!isInside(realRoot, resolved)) throw new Error(`user-rules file resolves outside the project root: ${relative}`);
|
|
406
|
+
return { bytes: await readFile(absolute) };
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function byteWitness(bytes) {
|
|
410
|
+
return Object.freeze({ sha256: sha256(bytes), bytes: bytes.length, contentBase64: bytes.toString("base64") });
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
function normalizeEntryId(value) {
|
|
414
|
+
const entryId = requiredText(value, "user-rules entry id is required");
|
|
415
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(entryId)) throw new Error("user-rules entry id is invalid");
|
|
416
|
+
return entryId;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function normalizeUserRulePath(value) {
|
|
420
|
+
const relative = normalizeProjectRelative(value);
|
|
421
|
+
if (!relative || !relative.startsWith(USER_RULES_CONTENT_ROOT)) throw new Error("user-rules entry must stay under dev/user_rules/");
|
|
422
|
+
return relative;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function normalizeProjectRelative(value) {
|
|
426
|
+
if (typeof value !== "string") return null;
|
|
427
|
+
const normalized = path.posix.normalize(value.replaceAll("\\", "/").replace(/^\.\//, ""));
|
|
428
|
+
if (!normalized || normalized === "." || normalized === ".." || normalized.startsWith("../") || path.posix.isAbsolute(normalized)) return null;
|
|
429
|
+
return normalized;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
function isInside(root, target) {
|
|
433
|
+
const relative = path.relative(path.resolve(root), path.resolve(target));
|
|
434
|
+
return Boolean(relative) && !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function decodeBase64(value, message) {
|
|
438
|
+
if (typeof value !== "string" || !/^[A-Za-z0-9+/]*={0,2}$/.test(value) || value.length % 4 !== 0) throw new Error(message);
|
|
439
|
+
const bytes = Buffer.from(value, "base64");
|
|
440
|
+
if (bytes.toString("base64") !== value) throw new Error(message);
|
|
441
|
+
return bytes;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function toBuffer(value, message) {
|
|
445
|
+
if (Buffer.isBuffer(value)) return Buffer.from(value);
|
|
446
|
+
if (typeof value === "string") return Buffer.from(value, "utf8");
|
|
447
|
+
throw new Error(message);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function requiredText(value, message) {
|
|
451
|
+
if (typeof value !== "string" || !value.trim()) throw new Error(message);
|
|
452
|
+
return value.trim();
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function sha256(value) {
|
|
456
|
+
return createHash("sha256").update(value).digest("hex");
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function count(text, fragment) {
|
|
460
|
+
return text.split(fragment).length - 1;
|
|
461
|
+
}
|
package/package.json
CHANGED
package/packs/closeout.md
CHANGED
|
@@ -28,7 +28,7 @@ Do not copy the full opening message into `dev/SESSION_LOG.md` or any third curr
|
|
|
28
28
|
2. Reconcile lifecycle state across `Completed This Session`, `Validation / QC`, `Next Priorities`, `Risks / Blockers`, and `Next Session Opening Message`. Completed or verified work cannot remain unresolved unless explicitly reclassified as monitor-only, follow-up scope, blocked, or reopened with its missing evidence or trigger.
|
|
29
29
|
The bundled doctor is a mechanical floor for obvious overlap and unresolved fields; it cannot prove that renamed or paraphrased work is semantically consistent. Read all five sections as a whole before marking the lifecycle field resolved. For governance, release, or another project-defined high-risk completion, use the project's independent semantic review gate in addition to doctor.
|
|
30
30
|
3. Make `Next Priorities` name one recommended next action and a short reason unless blocked or a real user decision is required.
|
|
31
|
-
4. Complete the persistence-routing
|
|
31
|
+
4. Complete the persistence-routing, handoff-sufficiency, `Closeout outcome`, and `Project-required persistence` fields. The next agent must be able to continue from `AGENTS.md`, the handoff, the project index when needed, and routed packs without searching old log history. `complete` is allowed only when all required writes/read-backs and any project-required persistence succeeded; use `not_required` only when that persistence is genuinely not required. If a required commit, push, release record, or equivalent persistence is blocked or not authorized, set both fields to `blocked` with the exact boundary.
|
|
32
32
|
5. Add one concise log entry for work actually performed. Record evidence disposition and the prompt-mirror verification result; omit the full opening message by design.
|
|
33
33
|
6. Update the project index and sync registry only when their owned maps or obligations changed. Record each applicable sync target as `confirmed`, `unverified`, `pending`, `blocked`, or `not_applicable`.
|
|
34
34
|
7. Record the actual root, Git root, branch, commit, worktrees / parallel workspaces, uncommitted changes, and unresolved drift. Do not clean or change them without separate authorization.
|
|
@@ -36,7 +36,8 @@ Do not copy the full opening message into `dev/SESSION_LOG.md` or any third curr
|
|
|
36
36
|
9. Run the short maintenance trigger check below and record its result in the log.
|
|
37
37
|
10. Mark first-use guidance `consumed` after the first successfully completed task or first full closeout. Upgrade must never reset `consumed` or `not_applicable` to `eligible`.
|
|
38
38
|
11. Regenerate `START_NEXT_SESSION_PROMPT.txt` from the sole fenced handoff opening-message block. Run the project's fixed prompt-mirror checker or perform an equivalent anchored read-back that verifies marker, heading, fence, full-copy uniqueness, and normalized content equality.
|
|
39
|
-
12. Run available project closeout
|
|
39
|
+
12. Run available project-specific closeout checks. Do not run a separate bundled `doctor`: the `closeout-status` command below performs the one required fresh doctor read-back. Do not treat an external update-check failure as local closeout failure. Fix state or mirror failures before claiming handoff ready.
|
|
40
|
+
13. Run `agent-handoff-kit closeout-status --root <project root>` after the handoff and prompt read-back. It performs the one required fresh doctor read-back and its output is the only final card source: copy its status faithfully. A nonzero result means the closeout is blocked; do not replace it with a success summary.
|
|
40
41
|
|
|
41
42
|
## Maintenance Trigger Check
|
|
42
43
|
|
|
@@ -52,21 +53,22 @@ If no trigger applies, record one no-op reason. Handoff carries continuity; log
|
|
|
52
53
|
|
|
53
54
|
The handoff opening-message block is authoritative. It must name the absolute root, route the agent through `AGENTS.md` and the handoff, state the current objective and boundary, and avoid instructing the next agent to redo completed work. It must not require SESSION_LOG as an ordinary startup read.
|
|
54
55
|
|
|
55
|
-
Use
|
|
56
|
+
Use `agent-handoff-kit closeout-status --root <project root>` after the required read-backs. It renders the verified version when available and otherwise `version unverified`; never print the literal placeholder `v<version>`, hand-compose a substitute card, or use `handoff saved` unless the command reports `status: complete`.
|
|
56
57
|
|
|
57
58
|
```text
|
|
58
|
-
/\_/\ Agent Handoff Kit v<version>
|
|
59
|
-
( -.- ) handoff saved
|
|
60
|
-
> ^ <
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
59
|
+
/\_/\ Agent Handoff Kit v<version>
|
|
60
|
+
( -.- ) handoff saved
|
|
61
|
+
> ^ <
|
|
62
|
+
|
|
63
|
+
status: complete
|
|
64
|
+
โ
Done: <completed summary>
|
|
65
|
+
๐ QC: <validation summary>
|
|
66
|
+
๐ Handoff: opening message ready
|
|
67
|
+
โ ๏ธ Boundary: <important boundary or none>
|
|
66
68
|
```
|
|
67
69
|
|
|
68
|
-
|
|
70
|
+
For `status: blocked`, the command instead says `handoff blocked`; retain that status and reason, then give the short local-root entry `Start Agent Handoff` / `้ๅทฅ` and the path-bearing fallback for an agent not yet pointed at the root. Do not hand-compose a third stateful prompt in the final response.
|
|
69
71
|
|
|
70
72
|
## Stop Conditions
|
|
71
73
|
|
|
72
|
-
Do not claim closeout complete when any required write or read-back failed, lifecycle state conflicts remain, the mirror is stale or duplicated, the root is uncertain, mandatory sync is unclassified, or required Git persistence was explicitly part of the project's closeout contract but did not succeed. State the exact blocker and leave the project in an honest resumable state.
|
|
74
|
+
Do not claim closeout complete when any required write or read-back failed, lifecycle state conflicts remain, the mirror is stale or duplicated, the root is uncertain, mandatory sync is unclassified, `closeout-status` is nonzero, or required Git persistence was explicitly part of the project's closeout contract but did not succeed. State the exact blocker and leave the project in an honest resumable state.
|
package/packs/communication.md
CHANGED
|
@@ -11,12 +11,14 @@ Use for reply format, language behavior, output schema, user-facing explanation,
|
|
|
11
11
|
|
|
12
12
|
## Rules
|
|
13
13
|
|
|
14
|
-
1. Match the user's language unless a project file requires another language.
|
|
15
|
-
2. Lead with decisions, findings, or results before background.
|
|
16
|
-
3.
|
|
17
|
-
4.
|
|
18
|
-
5.
|
|
19
|
-
6.
|
|
14
|
+
1. Match the user's language unless a project file requires another language.
|
|
15
|
+
2. Lead with decisions, findings, or results before background.
|
|
16
|
+
3. For an ordinary direct task, first state the result and practical effect in everyday language. Add a next step only when the user needs one; do not attach a repeated summary merely because the answer is short.
|
|
17
|
+
4. For a complex technical result, first give a short, clear conclusion and practical effect. Put exact commands, errors, hashes, source paths, and supporting evidence after the conclusion; when the user asks for technical depth, provide it without losing the clear takeaway.
|
|
18
|
+
5. Mark assumptions and unverified facts. Clear language never permits hiding uncertainty, safety risk, data loss, permission boundaries, or a blocked condition.
|
|
19
|
+
6. Keep operational instructions copy-paste-ready when they are meant for future sessions.
|
|
20
|
+
7. Avoid exposing internal process unless it helps the user act.
|
|
21
|
+
8. Give a clear recommended next step whenever the user needs to continue. If there is one best path, state it directly with a short reason. Offer two or three choices only when the user truly must decide; mark the recommended choice and do not turn an already-made technical judgment into an open question.
|
|
20
22
|
|
|
21
23
|
## Checks
|
|
22
24
|
|
package/packs/onboarding.md
CHANGED
|
@@ -24,7 +24,7 @@ Load this pack when the user message contains an onboarding signal such as:
|
|
|
24
24
|
|
|
25
25
|
### Continuity startup boundary
|
|
26
26
|
|
|
27
|
-
`Start Agent Handoff` / "้ๅทฅ" starts continuity and reads the current handoff state; it is not an onboarding signal.
|
|
27
|
+
`Start Agent Handoff` / "้ๅทฅ" starts continuity and reads the minimum current handoff state; it is not an onboarding signal. A plain startup stops after its status card and recommended next action; a loaded objective alone does not authorize work. A same-message concrete task may begin normally. Only when no executable objective remains after state reading should the AI ask one concise question or offer the guided onboarding path. Explicit requests such as "ๆฐๆ๏ผๆๆ็จ" enter onboarding directly.
|
|
28
28
|
|
|
29
29
|
### Implicit signals
|
|
30
30
|
|
|
@@ -11,7 +11,7 @@ Do not read `dev/SESSION_LOG.md` during ordinary startup; it is trace-back evide
|
|
|
11
11
|
Route intent in this order:
|
|
12
12
|
|
|
13
13
|
1. Clear closeout intent routes directly to `dev/rules/closeout.md`.
|
|
14
|
-
2. Clear continuity intent such as "้ๅทฅ", "Start Agent Handoff", "้ๅงๆฅๅ", or "continue handoff" resumes from the handoff.
|
|
14
|
+
2. Clear continuity intent such as "้ๅทฅ", "Start Agent Handoff", "้ๅงๆฅๅ", or "continue handoff" resumes the minimum current state from the handoff. A plain continuity message with no same-message task or explicit long-run instruction authorizes only that recovery, the startup card, the current objective/risk/recommended next action, and then the end of the turn. It does not authorize task-specific reads, research, plans, protocols, preflight, file searches, sub-agents, QA, packaging, writes, network access, or opt-out wording such as "unless you object I will start". A concrete objective found only in loaded state is not authority to complete it. A same-message task may begin normally. An explicit instruction such as "้ๅทฅ๏ผ็นผ็บๅๅฐไธไธๅ blocker" or "้ๅทฅ๏ผ็นผ็บๅฎๆ็ฎๅ็ฎๆจ" may continue under the normal task and safety rules.
|
|
15
15
|
3. A direct ordinary task begins without a startup card or onboarding ceremony. Read only the sources and packs required by that task.
|
|
16
16
|
4. Explicit guidance requests such as "I'm new", "teach me", "help me start", "ๆฐๆ", "ๆๆ็จ", or "้ป้ๅง" may load `dev/rules/onboarding.md`. A fresh install or short message only makes guidance available; it never overrides a concrete objective. If no executable objective remains after state reading, ask one concise question or offer guided onboarding.
|
|
17
17
|
|
|
@@ -25,7 +25,7 @@ Before a non-trivial task, identify and read the required local and external tru
|
|
|
25
25
|
|
|
26
26
|
Probe an integration only immediately before a task uses it, when the handoff explicitly identifies it as a dependency for the current objective, or when the user requests an integration health check. `TBD`, examples, blank rows, and undeclared placeholders are not installed integrations. Record `Last Verified` only after a real probe and through the normal persistence gate. Never write integration status merely because a session started.
|
|
27
27
|
|
|
28
|
-
Show the startup card only for explicit continuity startup.
|
|
28
|
+
Show the startup card only for explicit continuity startup. For a plain continuity message, show the card after the minimum state recovery and end the turn; its recommended next action is advice, not permission to act. An explicit same-message task or long-run continuation may combine the card with its first useful action. Direct ordinary tasks do not show the card. If onboarding is explicitly requested, combine any card and guidance in one response.
|
|
29
29
|
|
|
30
30
|
Use a verified version already present in loaded state. If obtaining it would require reading an otherwise unnecessary file, print `version unverified`; do not create a second version source merely to fill the card.
|
|
31
31
|
|
|
@@ -44,7 +44,9 @@ Use the full product name, plain user language, and one recommended next action.
|
|
|
44
44
|
|
|
45
45
|
## 2. Proportionate Work Loop
|
|
46
46
|
|
|
47
|
-
Apply PLAN โ READ โ CHANGE โ QC internally and in proportion to task state and risk. Do not make the user watch governance ceremony that does not help the task.
|
|
47
|
+
Apply PLAN โ READ โ CHANGE โ QC internally and in proportion to task state and risk. Do not make the user watch governance ceremony that does not help the task.
|
|
48
|
+
|
|
49
|
+
In every user-facing reply, lead with ordinary language: state the result and its practical effect, then the next action when one helps. Put exact commands, errors, hashes, and detailed evidence after that; brevity must not hide uncertainty or safety risk.
|
|
48
50
|
|
|
49
51
|
- Simple answers, pure conversation or creation with no durable state, and low-risk tasks with an obvious target may proceed directly with proportionate reading and checking.
|
|
50
52
|
- Non-trivial work reads relevant sources before changing them.
|
|
@@ -96,8 +98,9 @@ The always-enforced closeout invariants are:
|
|
|
96
98
|
1. Current state lives in `dev/SESSION_HANDOFF.md`; trace evidence lives in `dev/SESSION_LOG.md`.
|
|
97
99
|
2. Completed, pending, risk, validation, and opening-message lifecycle states agree.
|
|
98
100
|
3. `START_NEXT_SESSION_PROMPT.txt` is regenerated from the sole authoritative handoff block and no third full copy is retained.
|
|
99
|
-
4. Closeout is not complete until required files are written, read back, and the available closeout checks pass.
|
|
100
|
-
5.
|
|
101
|
+
4. Closeout is not complete until required files are written, read back, and the available closeout checks pass.
|
|
102
|
+
5. After those checks, render the final card with `agent-handoff-kit closeout-status --root <project root>`; only its `status: complete` output may say `handoff saved`. A nonzero / `blocked` result is an honest blocked closeout, not a completed one.
|
|
103
|
+
6. Git commit, push, release, publish, deployment, deletion, and permission changes remain separately authorized actions.
|
|
101
104
|
|
|
102
105
|
## 5. Pack Loading
|
|
103
106
|
|