@hassangameryt/freeflow 0.7.3 → 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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.cursor-plugin/plugin.json +1 -1
- package/NOTICE +14 -0
- package/README.md +26 -31
- package/capabilities/cognitive-routing/SKILL.md +106 -161
- package/capabilities/cognitive-routing/references/both-mode.md +36 -0
- package/capabilities/cognitive-routing/references/executor-mode.md +48 -0
- package/capabilities/cognitive-routing/references/helper-mode.md +47 -0
- package/capabilities/compaction/SKILL.md +49 -0
- package/capabilities/compaction/references/summary-format.md +239 -0
- package/command-surface.json +4 -0
- package/gemini-extension.json +1 -1
- package/hooks/shared/runtime-context.mjs +28 -30
- package/licenses/Apache-2.0.txt +55 -0
- package/package.json +22 -9
- package/pi-extension/README.md +41 -0
- package/pi-extension/dist/cognitive-routing/assembler.js +393 -0
- package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/config.js +5 -2
- package/pi-extension/dist/cognitive-routing/economics.js +45 -0
- package/pi-extension/dist/cognitive-routing/event-schema.js +388 -0
- package/pi-extension/dist/{session-sources/events.js → cognitive-routing/event-store.js} +103 -40
- package/pi-extension/dist/cognitive-routing/gate.js +241 -0
- package/pi-extension/dist/cognitive-routing/handlers.js +899 -0
- package/pi-extension/dist/cognitive-routing/handoffs.js +350 -0
- package/pi-extension/dist/cognitive-routing/model-control.js +467 -0
- package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/projection.js +229 -56
- package/pi-extension/dist/cognitive-routing/provenance.js +81 -0
- package/pi-extension/dist/cognitive-routing/runtime.js +396 -0
- package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/schemas.js +43 -7
- package/pi-extension/dist/cognitive-routing/session.js +221 -0
- package/pi-extension/dist/{session-sources → cognitive-routing}/sources.js +99 -85
- package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/state.js +37 -378
- package/pi-extension/dist/cognitive-routing/status.js +80 -0
- package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/tools.js +12 -12
- package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/types.js +5 -11
- package/pi-extension/dist/compaction/carry.js +191 -0
- package/pi-extension/dist/compaction/config.js +22 -0
- package/pi-extension/dist/compaction/controller.js +471 -0
- package/pi-extension/dist/compaction/harness.js +77 -0
- package/pi-extension/dist/compaction/results.js +158 -0
- package/pi-extension/dist/compaction/thresholds.js +35 -0
- package/pi-extension/dist/compaction/tool.js +57 -0
- package/pi-extension/dist/host/branch.js +13 -0
- package/pi-extension/dist/host/canonical.js +12 -0
- package/pi-extension/dist/host/catalog.js +77 -0
- package/pi-extension/dist/host/config.js +374 -0
- package/pi-extension/dist/host/projection-tags.js +60 -0
- package/pi-extension/dist/host/prompts.js +82 -0
- package/pi-extension/dist/{session-sources → host}/read-only-session.js +112 -1
- package/pi-extension/dist/{runtime → host}/request-history.js +121 -39
- package/pi-extension/dist/host/runtime-state.js +189 -0
- package/pi-extension/dist/{settings/settings-ui.js → host/settings/freeflow-command.js} +620 -410
- package/pi-extension/dist/{settings/settings-tui.js → host/settings/settings-view.js} +186 -73
- package/pi-extension/dist/host/staging.js +28 -0
- package/pi-extension/dist/host/status.js +101 -0
- package/pi-extension/dist/index.js +423 -173
- package/pi-extension/dist/provider-support/cache/anchor.js +21 -0
- package/pi-extension/dist/provider-support/cache/anthropic.js +102 -0
- package/pi-extension/dist/provider-support/cache/health.js +73 -0
- package/pi-extension/dist/provider-support/cache/index.js +58 -0
- package/pi-extension/dist/provider-support/cache/keepalive.js +210 -0
- package/pi-extension/dist/provider-support/cache/monitor.js +17 -0
- package/pi-extension/dist/provider-support/cache/openai-responses.js +48 -0
- package/pi-extension/dist/provider-support/effort.js +13 -0
- package/pi-extension/dist/provider-support/index.js +44 -3
- package/pi-extension/dist/provider-support/{astra → openai}/adapter.js +46 -29
- package/pi-extension/dist/provider-support/{astra → openai}/history.js +10 -8
- package/pi-extension/dist/provider-support/{astra → openai}/index.js +8 -4
- package/pi-extension/dist/provider-support/{astra → openai}/session-state.js +29 -38
- package/pi-extension/dist/provider-support/routes.js +17 -0
- package/pi-extension/dist/tool-execution/apply-patch/grammar.js +23 -0
- package/pi-extension/dist/tool-execution/apply-patch/match.js +38 -0
- package/pi-extension/dist/tool-execution/apply-patch/parser.js +177 -0
- package/pi-extension/dist/tool-execution/apply-patch/plan.js +201 -0
- package/pi-extension/dist/tool-execution/apply-patch/tool.js +84 -0
- package/pi-extension/dist/tool-execution/background.js +238 -0
- package/pi-extension/dist/tool-execution/bash-guard.js +23 -0
- package/pi-extension/dist/tool-execution/config.js +22 -0
- package/pi-extension/dist/tool-execution/edit-messages.js +120 -0
- package/pi-extension/dist/tool-execution/file-state.js +138 -0
- package/pi-extension/dist/tool-execution/file-tracking.js +143 -0
- package/pi-extension/dist/tool-execution/prompt.js +54 -0
- package/pi-extension/dist/tool-execution/tools.js +16 -0
- package/pi-extension/freeflow/README.md +9 -0
- package/plugin.json +1 -1
- package/runtime/prompts/cognitive-routing.md +4 -4
- package/runtime/prompts/core.md +22 -75
- package/runtime/prompts/interaction-contract.md +15 -8
- package/runtime/prompts/tool-execution.md +38 -0
- package/runtime/prompts/working-method.md +108 -0
- package/skills/action-selection/SKILL.md +39 -47
- package/skills/action-selection/references/trajectory-stalls.md +2 -0
- package/skills/bypass/SKILL.md +2 -2
- package/skills/commit-work/SKILL.md +31 -83
- package/skills/commit-work/references/git-state-edges.md +1 -1
- package/skills/commit-work/references/simple-push.md +2 -0
- package/skills/commit-work/references/staging-decisions.md +1 -1
- package/skills/decision-gate/SKILL.md +31 -50
- package/skills/design-for-depth/SKILL.md +44 -53
- package/skills/design-for-depth/references/design-pressure-signals.md +46 -144
- package/skills/design-for-depth/references/implementation-decisions.md +1 -1
- package/skills/design-for-depth/references/interface-design-loop.md +5 -36
- package/skills/design-for-depth/references/module-and-dependency-design.md +2 -32
- package/skills/design-for-depth/references/state-and-failure-boundaries.md +2 -13
- package/skills/diagnose-failure/SKILL.md +39 -24
- package/skills/diagnose-failure/references/diagnostic-loop-catalog.md +2 -0
- package/skills/diagnose-failure/references/flaky-and-performance-diagnosis.md +2 -2
- package/skills/discuss/SKILL.md +35 -11
- package/skills/discuss/references/discussion-continuity.md +7 -27
- package/skills/evaluate-skill/SKILL.md +49 -80
- package/skills/evaluate-skill/references/evaluation-definition-schema.md +35 -5
- package/skills/evaluate-skill/references/evaluation-design.md +14 -14
- package/skills/evaluate-skill/references/execution-and-evidence.md +26 -5
- package/skills/evaluate-skill/references/review-and-revision.md +3 -1
- package/skills/evaluate-skill/scripts/lib/definitions.mjs +49 -8
- package/skills/evaluate-skill/scripts/lib/pi.mjs +14 -7
- package/skills/evaluate-skill/scripts/lib/review.mjs +196 -0
- package/skills/evaluate-skill/scripts/lib/runner.mjs +45 -8
- package/skills/evaluate-skill/scripts/lib/sandbox.mjs +2 -0
- package/skills/evaluate-skill/scripts/lib/trials.mjs +103 -0
- package/skills/evaluate-skill/scripts/lib/view.mjs +67 -1
- package/skills/evaluate-skill/scripts/pi-command-tool.mjs +144 -0
- package/skills/evaluate-skill/scripts/pi-guard.mjs +30 -13
- package/skills/evaluate-skill/scripts/skill-eval.mjs +114 -34
- package/skills/execute-work/SKILL.md +41 -9
- package/skills/execute-work/references/code-practices.md +2 -0
- package/skills/execute-work/references/execute-work-edges.md +11 -1
- package/skills/handoff/SKILL.md +1 -1
- package/skills/handoff/references/handoff-templates.md +1 -1
- package/skills/review-artifact/SKILL.md +42 -41
- package/skills/review-artifact/references/adjudicate-artifact-review.md +1 -1
- package/skills/review-artifact/references/independent-artifact-reviewer-contract.md +1 -1
- package/skills/review-work/SKILL.md +38 -32
- package/skills/review-work/references/adjudicate-work-review.md +1 -1
- package/skills/review-work/references/independent-work-reviewer-contract.md +1 -1
- package/skills/review-work/references/security-risk-lens.md +2 -4
- package/skills/setup-freeflow/SKILL.md +3 -1
- package/skills/setup-freeflow/references/activation-contract.md +7 -13
- package/skills/setup-freeflow/references/host-setup.md +3 -3
- package/skills/track-work/SKILL.md +113 -161
- package/skills/track-work/references/working-record-format.md +189 -350
- package/skills/track-work/scripts/lib/document.mjs +62 -6
- package/skills/track-work/scripts/lib/format.mjs +16 -1
- package/skills/track-work/scripts/lib/store.mjs +9 -8
- package/skills/track-work/scripts/lib/transitions.mjs +79 -4
- package/skills/track-work/scripts/working-record.mjs +34 -12
- package/skills/verify-work/SKILL.md +29 -20
- package/skills/verify-work/references/browser-runtime-evidence.md +1 -5
- package/skills/verify-work/references/integration-evidence.md +2 -0
- package/skills/verify-work/references/performance-evidence.md +3 -1
- package/skills/verify-work/references/test-design.md +3 -1
- package/skills/workflow/SKILL.md +65 -21
- package/skills/workflow/references/domain-skill-composition.md +5 -3
- package/skills/write-docs/SKILL.md +83 -0
- package/skills/write-docs/references/documentation-shapes.md +119 -0
- package/skills/write-docs/scripts/docs-check.mjs +139 -0
- package/skills/write-plan/SKILL.md +40 -40
- package/skills/write-plan/references/plan-shapes.md +1 -1
- package/skills/write-skill/SKILL.md +107 -147
- package/skills/write-skill/references/activation-boundaries.md +2 -0
- package/skills/write-skill/references/agent-first-instructions.md +22 -10
- package/skills/write-skill/references/progressive-disclosure.md +4 -2
- package/skills/write-skill/references/skill-dependency-graphs.md +2 -0
- package/skills/write-skill/scripts/lib/similarity.mjs +56 -0
- package/skills/write-skill/scripts/skill-author.mjs +18 -2
- package/skills/write-spec/SKILL.md +34 -41
- package/skills/write-spec/references/artifact-standards.md +1 -1
- package/skills/write-spec/references/decision-records.md +2 -0
- package/skills/write-spec/references/spec-shapes.md +1 -1
- package/capabilities/context-virtualization/SKILL.md +0 -103
- package/capabilities/conversation-history/SKILL.md +0 -53
- package/hooks/tests/check-host-adapters.test.mjs +0 -82
- package/hooks/tests/check-runtime-context-hook.sh +0 -212
- package/pi-extension/dist/cognitive-routing-v2/runtime.js +0 -2181
- package/pi-extension/dist/context-virtualization/commands.js +0 -89
- package/pi-extension/dist/context-virtualization/projector.js +0 -42
- package/pi-extension/dist/context-virtualization/runtime.js +0 -378
- package/pi-extension/dist/context-virtualization/state.js +0 -57
- package/pi-extension/dist/context-virtualization/types.js +0 -10
- package/pi-extension/dist/conversation-history/passages.js +0 -66
- package/pi-extension/dist/conversation-history/ranking.js +0 -105
- package/pi-extension/dist/conversation-history/runtime.js +0 -226
- package/pi-extension/dist/conversation-history/search.js +0 -56
- package/pi-extension/dist/conversation-history/types.js +0 -1
- package/pi-extension/dist/freeflow-context/resolver.js +0 -120
- package/pi-extension/dist/freeflow-context/runtime.js +0 -80
- package/pi-extension/dist/freeflow-context/source-projector.js +0 -95
- package/pi-extension/dist/freeflow-context/tool.js +0 -314
- package/pi-extension/dist/freeflow-context/types.js +0 -12
- package/pi-extension/dist/freeflow-context/visibility.js +0 -28
- package/pi-extension/dist/integrations/mcp-config.js +0 -29
- package/pi-extension/dist/runtime/runtime-context.js +0 -754
- package/pi-extension/dist/runtime/runtime-identity.js +0 -5
- package/pi-extension/dist/session-sources/provenance.js +0 -32
- package/pi-extension/dist/ui/text-component.js +0 -57
- package/pi-extension/src/cognitive-routing-v2/budget.ts +0 -42
- package/pi-extension/src/cognitive-routing-v2/config.ts +0 -173
- package/pi-extension/src/cognitive-routing-v2/projection.ts +0 -375
- package/pi-extension/src/cognitive-routing-v2/render.ts +0 -277
- package/pi-extension/src/cognitive-routing-v2/runtime.ts +0 -2241
- package/pi-extension/src/cognitive-routing-v2/schemas.ts +0 -180
- package/pi-extension/src/cognitive-routing-v2/state.ts +0 -839
- package/pi-extension/src/cognitive-routing-v2/tools.ts +0 -62
- package/pi-extension/src/cognitive-routing-v2/types.ts +0 -254
- package/pi-extension/src/context-virtualization/commands.ts +0 -111
- package/pi-extension/src/context-virtualization/projector.ts +0 -62
- package/pi-extension/src/context-virtualization/runtime.ts +0 -428
- package/pi-extension/src/context-virtualization/state.ts +0 -79
- package/pi-extension/src/context-virtualization/types.ts +0 -92
- package/pi-extension/src/conversation-history/passages.ts +0 -81
- package/pi-extension/src/conversation-history/ranking.ts +0 -155
- package/pi-extension/src/conversation-history/runtime.ts +0 -250
- package/pi-extension/src/conversation-history/search.ts +0 -79
- package/pi-extension/src/conversation-history/types.ts +0 -31
- package/pi-extension/src/freeflow-context/resolver.ts +0 -139
- package/pi-extension/src/freeflow-context/runtime.ts +0 -100
- package/pi-extension/src/freeflow-context/source-projector.ts +0 -106
- package/pi-extension/src/freeflow-context/tool.ts +0 -366
- package/pi-extension/src/freeflow-context/types.ts +0 -70
- package/pi-extension/src/freeflow-context/visibility.ts +0 -53
- package/pi-extension/src/index.ts +0 -390
- package/pi-extension/src/integrations/mcp-config.ts +0 -32
- package/pi-extension/src/provider-support/astra/adapter.ts +0 -108
- package/pi-extension/src/provider-support/astra/history.ts +0 -145
- package/pi-extension/src/provider-support/astra/index.ts +0 -12
- package/pi-extension/src/provider-support/astra/session-state.ts +0 -113
- package/pi-extension/src/provider-support/index.ts +0 -5
- package/pi-extension/src/runtime/request-history.ts +0 -243
- package/pi-extension/src/runtime/runtime-context.ts +0 -860
- package/pi-extension/src/runtime/runtime-identity.ts +0 -8
- package/pi-extension/src/session-sources/events.ts +0 -230
- package/pi-extension/src/session-sources/provenance.ts +0 -39
- package/pi-extension/src/session-sources/read-only-session.ts +0 -170
- package/pi-extension/src/session-sources/sources.ts +0 -334
- package/pi-extension/src/settings/settings-tui.ts +0 -501
- package/pi-extension/src/settings/settings-ui.ts +0 -1652
- package/pi-extension/src/ui/text-component.ts +0 -66
- package/pi-extension/tests/cache-reuse/history.test.js +0 -117
- package/pi-extension/tests/cache-reuse/native.test.js +0 -91
- package/pi-extension/tests/cache-reuse/settings.test.js +0 -211
- package/pi-extension/tests/cognitive-routing-v2/communication.test.js +0 -577
- package/pi-extension/tests/cognitive-routing-v2/compaction-input.test.js +0 -183
- package/pi-extension/tests/cognitive-routing-v2/delegation.test.js +0 -557
- package/pi-extension/tests/cognitive-routing-v2/native.test.js +0 -474
- package/pi-extension/tests/cognitive-routing-v2/performance.test.js +0 -87
- package/pi-extension/tests/cognitive-routing-v2/persistence.test.js +0 -300
- package/pi-extension/tests/cognitive-routing-v2/projection.test.js +0 -241
- package/pi-extension/tests/cognitive-routing-v2/recovery.test.js +0 -1034
- package/pi-extension/tests/cognitive-routing-v2/render.test.js +0 -244
- package/pi-extension/tests/cognitive-routing-v2/runtime.test.js +0 -423
- package/pi-extension/tests/cognitive-routing-v2/stabilization.test.js +0 -521
- package/pi-extension/tests/cognitive-routing-v2/state.test.js +0 -586
- package/pi-extension/tests/context-virtualization/extension.test.js +0 -775
- package/pi-extension/tests/context-virtualization/projector.test.js +0 -110
- package/pi-extension/tests/context-virtualization/runtime.test.js +0 -230
- package/pi-extension/tests/conversation-history/runtime.test.js +0 -98
- package/pi-extension/tests/conversation-history/search.test.js +0 -97
- package/pi-extension/tests/fixtures/pi-host.js +0 -4
- package/pi-extension/tests/fixtures/routing-native.js +0 -191
- package/pi-extension/tests/integration/mode-free-core.test.js +0 -220
- package/pi-extension/tests/integration/pi-extension.test.js +0 -1447
- package/pi-extension/tests/integration/prompt-architecture.test.js +0 -447
- package/pi-extension/tests/integration/unaffected-regressions.test.js +0 -478
- package/pi-extension/tests/provider-support/astra-boundaries.test.js +0 -75
- package/pi-extension/tests/provider-support/astra.test.js +0 -306
- package/pi-extension/tests/provider-support/cli.test.js +0 -92
- package/pi-extension/tests/provider-support/native.test.js +0 -183
- package/pi-extension/tests/settings/settings-tui.test.js +0 -243
- package/pi-extension/tsconfig.json +0 -16
- package/runtime/prompts/context-virtualization.md +0 -3
- package/runtime/prompts/conversation-history.md +0 -3
- package/skills/design-for-depth/references/software-design-philosophy.md +0 -202
- /package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/budget.js +0 -0
- /package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/render.js +0 -0
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { resolveToolPath } from "../tool-execution/file-state.js";
|
|
3
|
+
import {
|
|
4
|
+
carryBudget,
|
|
5
|
+
carryProblem,
|
|
6
|
+
estimateTokens,
|
|
7
|
+
isCarryResult,
|
|
8
|
+
latestUserMessages,
|
|
9
|
+
readCarriedFile,
|
|
10
|
+
renderCarried,
|
|
11
|
+
renderCarriedForCoordinator,
|
|
12
|
+
renderListed,
|
|
13
|
+
SUMMARY_LIMIT_TOKENS,
|
|
14
|
+
} from "./carry.js";
|
|
15
|
+
import { cycleFiles, harnessPart, nextCycle, previousFileLists, sessionFileLists } from "./harness.js";
|
|
16
|
+
import {
|
|
17
|
+
INDEX_TOKEN_BOUND,
|
|
18
|
+
renderIndex,
|
|
19
|
+
resolveResult,
|
|
20
|
+
resultFirstLine,
|
|
21
|
+
resultIndex,
|
|
22
|
+
scopeResults,
|
|
23
|
+
} from "./results.js";
|
|
24
|
+
import { cachedBranch } from "../host/branch.js";
|
|
25
|
+
/**
|
|
26
|
+
* Freeflow compaction's agent path. After each turn Freeflow measures the context and, once per cycle each, says
|
|
27
|
+
* compaction is due (the warning, with the result index) and then to compact now. The agent asks to compact with
|
|
28
|
+
* freeflow_compact once compaction is due. At the end of that turn Freeflow writes Pi's compaction entry, keeping
|
|
29
|
+
* nothing raw, followed by the carried context and a recovery message, and asks Pi to continue the same run. Pi fires
|
|
30
|
+
* no compaction events for this, so the caller runs Freeflow's post-compaction resets before the next request
|
|
31
|
+
* (takeCompacted).
|
|
32
|
+
*/
|
|
33
|
+
export const CARRIED_TYPE = "freeflow-carried-context";
|
|
34
|
+
export const RECOVERY_TYPE = "freeflow-compaction-recovery";
|
|
35
|
+
/** What /freeflow compact sends as the user's message; a list of results may follow it. */
|
|
36
|
+
export const USER_REQUEST =
|
|
37
|
+
"Compact now: read the compaction skill, prepare the next cycle, and call freeflow_compact.";
|
|
38
|
+
const ABNORMAL_STOPS = new Set(["error", "aborted", "length"]);
|
|
39
|
+
/** The most results the carried context lists by ref; the newest are listed. */
|
|
40
|
+
const MAX_LISTED = 60;
|
|
41
|
+
/** "Compact now" repeats as the context keeps growing, so a long step that passed it is reminded before Pi compacts. */
|
|
42
|
+
const COMPACT_NOW_REPEAT = 10_000;
|
|
43
|
+
const hash = (text) => createHash("sha256").update(text).digest("hex");
|
|
44
|
+
const branchOf = (ctx) => cachedBranch(ctx.sessionManager);
|
|
45
|
+
const cycleOf = (branch) => nextCycle(branch) - 1;
|
|
46
|
+
export class CompactionController {
|
|
47
|
+
host;
|
|
48
|
+
/** The user ran /freeflow compact in this cycle. */
|
|
49
|
+
requested;
|
|
50
|
+
/** Notices sent in the current cycle. */
|
|
51
|
+
sent = { cycle: 0, warning: false };
|
|
52
|
+
pending;
|
|
53
|
+
compacted;
|
|
54
|
+
constructor(host) {
|
|
55
|
+
this.host = host;
|
|
56
|
+
}
|
|
57
|
+
/** Session start or shutdown: nothing is due, scheduled or waiting to reset. */
|
|
58
|
+
reset() {
|
|
59
|
+
this.requested = undefined;
|
|
60
|
+
this.sent = { cycle: 0, warning: false };
|
|
61
|
+
this.pending = undefined;
|
|
62
|
+
this.compacted = undefined;
|
|
63
|
+
}
|
|
64
|
+
/** The user's /freeflow compact: compaction is due now, in this cycle. */
|
|
65
|
+
requestByUser(ctx) {
|
|
66
|
+
this.requested = cycleOf(branchOf(ctx));
|
|
67
|
+
}
|
|
68
|
+
/** Due when the user asked in this cycle, or the context has reached the warning point. */
|
|
69
|
+
isDue(ctx) {
|
|
70
|
+
if (this.requested === cycleOf(branchOf(ctx))) return true;
|
|
71
|
+
const measured = this.host.measure(ctx);
|
|
72
|
+
return measured !== undefined && measured.tokens >= measured.thresholds.warning;
|
|
73
|
+
}
|
|
74
|
+
/** The compaction part of /freeflow status: the cycle, context against each point, and the last compaction. */
|
|
75
|
+
statusText(ctx) {
|
|
76
|
+
if (!this.host.effective()) return undefined;
|
|
77
|
+
const branch = branchOf(ctx);
|
|
78
|
+
const k = (tokens) => `${Math.round(tokens / 1000)}k`;
|
|
79
|
+
const parts = [`cycle ${cycleOf(branch)}`];
|
|
80
|
+
const measured = this.host.measure(ctx);
|
|
81
|
+
if (measured) {
|
|
82
|
+
const { tokens, thresholds } = measured;
|
|
83
|
+
parts.push(
|
|
84
|
+
`context about ${k(tokens)} of ${k(thresholds.window)} (warning ${k(thresholds.warning)}, compact now ${k(thresholds.compactNow)}, Pi compacts at ${k(thresholds.trigger)})`,
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
const index = branch.map((entry) => entry?.type).lastIndexOf("compaction");
|
|
88
|
+
if (index >= 0) {
|
|
89
|
+
const freeflow = branch[index].details?.freeflow;
|
|
90
|
+
const carried = branch
|
|
91
|
+
.slice(index + 1)
|
|
92
|
+
.find((entry) => entry?.type === "custom_message" && entry.customType === CARRIED_TYPE);
|
|
93
|
+
const kind = !freeflow ? "Pi" : freeflow.fallback ? "Pi with Freeflow's additions" : "Freeflow";
|
|
94
|
+
parts.push(
|
|
95
|
+
`last compaction: ${kind}${carried ? `, carried about ${k(estimateTokens(String(carried.content ?? "")))}` : ""}`,
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
return parts.join(", ");
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* The result list for this cycle, or "" when none is needed: context reuse is off, or routing's refs already name
|
|
102
|
+
* every result in the agent's context.
|
|
103
|
+
*/
|
|
104
|
+
indexText(ctx) {
|
|
105
|
+
if (!this.host.carryEnabled() || this.host.nativeRefs()) return "";
|
|
106
|
+
return renderIndex(resultIndex(branchOf(ctx)));
|
|
107
|
+
}
|
|
108
|
+
/** The carry budget for this context: from the window, capped by the room before the warning. */
|
|
109
|
+
budget(ctx) {
|
|
110
|
+
return carryBudget(ctx.model?.contextWindow, this.host.measure(ctx)?.thresholds.warning);
|
|
111
|
+
}
|
|
112
|
+
/** How the notices tell the agent what it may carry. */
|
|
113
|
+
carryText(ctx) {
|
|
114
|
+
if (!this.host.carryEnabled())
|
|
115
|
+
return "context reuse is off, so carry nothing; the user's latest messages are carried for you";
|
|
116
|
+
const how = this.host.nativeRefs()
|
|
117
|
+
? "tool results by their routing ref such as ctx:1a2b3c4d, files by path"
|
|
118
|
+
: "tool results by id below, files by path";
|
|
119
|
+
return `pick older work you will need (budget ${this.budget(ctx)} tokens; Freeflow adds your newest results itself; ${how})`;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* After a turn: the notice to deliver. The warning comes once per cycle; "compact now" comes when the context
|
|
123
|
+
* crosses its point and again each time it grows another COMPACT_NOW_REPEAT tokens.
|
|
124
|
+
*/
|
|
125
|
+
observe(ctx, turn) {
|
|
126
|
+
if (!this.host.effective()) return undefined;
|
|
127
|
+
const branch = branchOf(ctx);
|
|
128
|
+
const cycle = cycleOf(branch);
|
|
129
|
+
if (this.sent.cycle !== cycle) this.sent = { cycle, warning: false };
|
|
130
|
+
const measured = this.host.measure(ctx, turn);
|
|
131
|
+
if (!measured) return undefined;
|
|
132
|
+
const { tokens: measuredTokens, thresholds } = measured;
|
|
133
|
+
// A list inserted with the notice is context too, so it moves the point earlier by its own size. Far below the
|
|
134
|
+
// warning it cannot reach it, so the list is built only near the point.
|
|
135
|
+
const nearWarning = measuredTokens + INDEX_TOKEN_BOUND >= thresholds.warning;
|
|
136
|
+
const listTokens = this.sent.warning || !nearWarning ? 0 : estimateTokens(this.indexText(ctx));
|
|
137
|
+
const tokens = measuredTokens + listTokens;
|
|
138
|
+
const level = tokens >= thresholds.compactNow ? "compactNow" : tokens >= thresholds.warning ? "warning" : undefined;
|
|
139
|
+
if (!level) return undefined;
|
|
140
|
+
if (level === "warning" && this.sent.warning) return undefined;
|
|
141
|
+
const repeat = level === "compactNow" && this.sent.compactNowAt !== undefined;
|
|
142
|
+
if (repeat && tokens < this.sent.compactNowAt + COMPACT_NOW_REPEAT) return undefined;
|
|
143
|
+
const withList = !this.sent.warning || (level === "compactNow" && !repeat);
|
|
144
|
+
this.sent.warning = true;
|
|
145
|
+
if (level === "compactNow") this.sent.compactNowAt = tokens;
|
|
146
|
+
return { level, text: this.noticeText(level, tokens, thresholds, ctx, withList) };
|
|
147
|
+
}
|
|
148
|
+
noticeText(level, tokens, thresholds, ctx, withList = true) {
|
|
149
|
+
const prefix = this.host.noticePrefix;
|
|
150
|
+
const { window, trigger } = thresholds;
|
|
151
|
+
if (this.host.coordinatorUnderProjection())
|
|
152
|
+
return `${prefix} ${level === "compactNow" ? "Compact now" : "Compaction is due soon"}: the full history is about ${tokens} of ${window} tokens, and Pi compacts on its own past about ${trigger}. Your view leaves out what workers did, so do not compact yourself: ${level === "compactNow" ? "now" : "at a safe point (after the current assessment, or before the next assignment)"}, delegate an assignment asking the worker to read the compaction skill, compact with freeflow_compact, and then return with freeflow_return; then continue.`;
|
|
153
|
+
const index = withList ? this.indexText(ctx) : "";
|
|
154
|
+
const list = index ? `\n\n${index}` : "";
|
|
155
|
+
// A worker's return hands the same history to the Coordinator and the next assignment, so it ends no growth.
|
|
156
|
+
const worker = this.host.routingAssignment() !== undefined;
|
|
157
|
+
if (level === "compactNow")
|
|
158
|
+
return `${prefix} Compact now: context is at about ${tokens} of ${window} tokens. Pi compacts on its own past about ${trigger}, or when a request overflows the model's window. The end of your current step is the safe point: write down any partial state, then prepare and call freeflow_compact; ${worker ? "compact before you return, since the Coordinator and the next assignment continue this history; " : ""}if Pi compacts first, its own summary replaces yours.${list}`;
|
|
159
|
+
// Before compact now there is room for the Coordinator's next turn, so a worker may finish a return first.
|
|
160
|
+
const end = `If you are at one now, compact now; if your work ends within a step or two with ${worker ? "a return" : "a final answer"}, finish it instead.`;
|
|
161
|
+
return `${prefix} Compaction is due soon: context is at about ${tokens} of ${window} tokens, and Pi compacts on its own past about ${trigger}. Keep working until a safe point: a finished step whose result you know (a check read, an edit set complete, a report written), not mid-edit or with a command running. ${end} At the safe point, read the compaction skill, update the Working Record, ${this.carryText(ctx)}, write the summary, and call freeflow_compact. A "compact now" notice follows near Pi's limit.${list}`;
|
|
162
|
+
}
|
|
163
|
+
/** Check a freeflow_compact call and schedule it for the end of this turn; throws with the reason it is refused. */
|
|
164
|
+
async request(params, ctx) {
|
|
165
|
+
if (!this.host.effective()) throw new Error("Freeflow compaction is turned off.");
|
|
166
|
+
if (this.host.coordinatorUnderProjection())
|
|
167
|
+
throw new Error(
|
|
168
|
+
"Your view leaves out what workers did, so do not compact yourself: delegate an assignment asking the worker to read the compaction skill, compact with freeflow_compact, and then return with freeflow_return.",
|
|
169
|
+
);
|
|
170
|
+
if (!this.isDue(ctx)) throw new Error(notDueText(branchOf(ctx)));
|
|
171
|
+
const summary = typeof params?.summary === "string" ? params.summary.trim() : "";
|
|
172
|
+
if (!summary) throw new Error("Write the summary before compacting: summary must not be empty.");
|
|
173
|
+
const summaryTokens = estimateTokens(summary);
|
|
174
|
+
if (summaryTokens > SUMMARY_LIMIT_TOKENS)
|
|
175
|
+
throw new Error(
|
|
176
|
+
`The summary is about ${summaryTokens} tokens; the limit is ${SUMMARY_LIMIT_TOKENS}. Shorten it by about ${summaryTokens - SUMMARY_LIMIT_TOKENS} tokens and call freeflow_compact again.`,
|
|
177
|
+
);
|
|
178
|
+
const carry = params?.carry === undefined ? [] : params.carry;
|
|
179
|
+
if (!Array.isArray(carry)) throw new Error("carry must be a list of { file, lines? } or { result } items.");
|
|
180
|
+
if (carry.length && !this.host.carryEnabled())
|
|
181
|
+
throw new Error(
|
|
182
|
+
"Context reuse is off: call freeflow_compact without carry. The user's latest messages are carried for you.",
|
|
183
|
+
);
|
|
184
|
+
const problems = carry.map(carryProblem).filter(Boolean);
|
|
185
|
+
if (problems.length) throw new Error(`Fix the carry list: ${problems.join("; ")}.`);
|
|
186
|
+
const { files, results, missing } = await this.read(carry, ctx);
|
|
187
|
+
const unreadable = files.filter((file) => "error" in file);
|
|
188
|
+
if (unreadable.length || missing.length)
|
|
189
|
+
throw new Error(
|
|
190
|
+
`These cannot be carried: ${[
|
|
191
|
+
...unreadable.map((file) => `${file.path} (${file.error})`),
|
|
192
|
+
...missing.map(
|
|
193
|
+
(id) =>
|
|
194
|
+
`${id} (${this.host.nativeRefs() ? "no routing ref of a carryable tool result" : "no such result"})`,
|
|
195
|
+
),
|
|
196
|
+
].join(", ")}. Remove or correct them.`,
|
|
197
|
+
);
|
|
198
|
+
const carriedTokens =
|
|
199
|
+
files.reduce((sum, file) => sum + ("text" in file ? estimateTokens(file.text) : 0), 0) +
|
|
200
|
+
results.reduce((sum, result) => sum + result.tokens, 0);
|
|
201
|
+
const budget = this.budget(ctx);
|
|
202
|
+
if (carriedTokens > budget)
|
|
203
|
+
throw new Error(
|
|
204
|
+
`The carried items are about ${carriedTokens} tokens; the budget is ${budget}. Drop or narrow about ${carriedTokens - budget} tokens (line ranges help) and re-read the rest during recovery.`,
|
|
205
|
+
);
|
|
206
|
+
this.pending = { summary, carry };
|
|
207
|
+
return `Compaction will happen at the end of this turn: about ${carriedTokens} tokens carried. The run then continues from the summary, the carried context and a recovery message.`;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Under Cognitive Routing, the current assignment's results by ref for Pi's own compaction, which copies nothing
|
|
211
|
+
* itself: without it a worker cannot tell its earlier results are still stored and re-reads them.
|
|
212
|
+
*/
|
|
213
|
+
assignmentList(branch) {
|
|
214
|
+
const assignment = this.host.nativeRefs() ? this.host.assignmentResults() : undefined;
|
|
215
|
+
if (!assignment) return "";
|
|
216
|
+
const listed = scopeResults(branch, assignment)
|
|
217
|
+
.slice(0, MAX_LISTED)
|
|
218
|
+
.map((result) => ({ ...result, selected: assignment.selected.has(result.id) }));
|
|
219
|
+
return renderListed(
|
|
220
|
+
listed,
|
|
221
|
+
"assignment",
|
|
222
|
+
"Results",
|
|
223
|
+
"Pi kept the most recent as they were; all are still stored: select one as evidence by its ref, or read it again if you need its content.",
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* The automatic part of carry and the list of what stays behind. After the agent's picks, the newest results of the
|
|
228
|
+
* work in progress (the current assignment under Cognitive Routing, otherwise this cycle) fill the rest of the
|
|
229
|
+
* budget; the others are listed by ref so the agent knows what exists. With context reuse off nothing is copied, and
|
|
230
|
+
* only routing keeps the list, which it needs for evidence selection.
|
|
231
|
+
*/
|
|
232
|
+
fill(branch, ctx, files, picked) {
|
|
233
|
+
const assignment = this.host.nativeRefs() ? this.host.assignmentResults() : undefined;
|
|
234
|
+
const carryOn = this.host.carryEnabled();
|
|
235
|
+
if (!carryOn && !assignment) return { automatic: [], listed: [] };
|
|
236
|
+
// A file the agent carries fresh makes any earlier read of it stale: those reads are neither copied nor listed.
|
|
237
|
+
const freshFiles = new Set(files.map((file) => resolveToolPath(file.path, ctx.cwd)));
|
|
238
|
+
const scope = scopeResults(branch, assignment).filter(
|
|
239
|
+
(result) => !(result.tool === "read" && result.path && freshFiles.has(resolveToolPath(result.path, ctx.cwd))),
|
|
240
|
+
);
|
|
241
|
+
const pickedIds = new Set(picked.map((result) => result.id));
|
|
242
|
+
let room = carryOn
|
|
243
|
+
? this.budget(ctx) -
|
|
244
|
+
files.reduce((sum, file) => sum + ("text" in file ? estimateTokens(file.text) : 0), 0) -
|
|
245
|
+
picked.reduce((sum, result) => sum + result.tokens, 0)
|
|
246
|
+
: 0;
|
|
247
|
+
const automatic = [];
|
|
248
|
+
for (const result of scope) {
|
|
249
|
+
if (pickedIds.has(result.id) || result.tokens > room) continue;
|
|
250
|
+
automatic.push(result);
|
|
251
|
+
room -= result.tokens;
|
|
252
|
+
}
|
|
253
|
+
const carried = new Set([...pickedIds, ...automatic.map((result) => result.id)]);
|
|
254
|
+
const listed = scope
|
|
255
|
+
.filter((result) => !carried.has(result.id))
|
|
256
|
+
.slice(0, MAX_LISTED)
|
|
257
|
+
.map((result) => ({ ...result, selected: assignment?.selected.has(result.id) === true }));
|
|
258
|
+
return { automatic, listed };
|
|
259
|
+
}
|
|
260
|
+
async read(carry, ctx) {
|
|
261
|
+
const branch = branchOf(ctx);
|
|
262
|
+
const files = await Promise.all(
|
|
263
|
+
carry.filter((item) => !isCarryResult(item)).map((item) => readCarriedFile(item, ctx.cwd)),
|
|
264
|
+
);
|
|
265
|
+
const ids = carry.filter(isCarryResult).map((item) => item.result);
|
|
266
|
+
const resolve = (id) => {
|
|
267
|
+
if (!this.host.nativeRefs()) return resolveResult(branch, id);
|
|
268
|
+
const source = this.host.resolveRef(id);
|
|
269
|
+
const firstLine = resultFirstLine(branch, id.replace(/^ctx:/, ""));
|
|
270
|
+
return (
|
|
271
|
+
source && {
|
|
272
|
+
id,
|
|
273
|
+
tool: source.tool,
|
|
274
|
+
label: id,
|
|
275
|
+
tokens: estimateTokens(source.text),
|
|
276
|
+
text: source.text,
|
|
277
|
+
...(firstLine === undefined ? {} : { firstLine }),
|
|
278
|
+
}
|
|
279
|
+
);
|
|
280
|
+
};
|
|
281
|
+
const results = ids.map(resolve).filter(Boolean);
|
|
282
|
+
const missing = ids.filter((id) => !results.some((result) => result.id === id));
|
|
283
|
+
return { files, results, missing };
|
|
284
|
+
}
|
|
285
|
+
/** At turn end, the entries that compact the session, or undefined when nothing is scheduled. */
|
|
286
|
+
async turnEnd(event, ctx) {
|
|
287
|
+
const pending = this.pending;
|
|
288
|
+
this.pending = undefined;
|
|
289
|
+
if (!pending || !this.host.effective()) return undefined;
|
|
290
|
+
// A turn that failed or was cut off may not have finished preparing; compaction stays due.
|
|
291
|
+
if (ABNORMAL_STOPS.has(event?.message?.stopReason)) return undefined;
|
|
292
|
+
const branch = branchOf(ctx);
|
|
293
|
+
const cycle = nextCycle(branch);
|
|
294
|
+
const requestedBy = this.requested === cycleOf(branch) ? "user" : "notice";
|
|
295
|
+
const { files, results } = await this.read(pending.carry, ctx);
|
|
296
|
+
const previous = previousCarried(branch);
|
|
297
|
+
const summary = `${pending.summary}\n\n${harnessPart({
|
|
298
|
+
cycle,
|
|
299
|
+
requestedBy,
|
|
300
|
+
routingProfile: this.host.routingProfile(),
|
|
301
|
+
background: this.host.background(),
|
|
302
|
+
files: sessionFileLists(branch),
|
|
303
|
+
})}`;
|
|
304
|
+
const userMessages = latestUserMessages(branch, (message) => message.startsWith(USER_REQUEST));
|
|
305
|
+
const { automatic, listed } = this.fill(branch, ctx, files, results);
|
|
306
|
+
const carriedText = renderCarried(this.host.noticePrefix, cycle, userMessages, files, [...results, ...automatic], {
|
|
307
|
+
listed,
|
|
308
|
+
scope: this.host.nativeRefs() && this.host.assignmentResults() ? "assignment" : "cycle",
|
|
309
|
+
});
|
|
310
|
+
const recovery = `${this.host.noticePrefix} ${recoveryText(cycle, "The carried context is above: its files were read at compaction, so do not read them or its results again unless something has changed them since. ")} ${AFTER_REQUESTED}`;
|
|
311
|
+
this.requested = undefined;
|
|
312
|
+
this.compacted = { carriedFiles: files.filter((file) => "text" in file).map((file) => file.path) };
|
|
313
|
+
return {
|
|
314
|
+
entries: [
|
|
315
|
+
{
|
|
316
|
+
type: "compaction",
|
|
317
|
+
summary,
|
|
318
|
+
firstKeptEntryId: null,
|
|
319
|
+
details: {
|
|
320
|
+
// Pi's own details shape, so later compactions (Pi's or Freeflow's) carry the lists forward.
|
|
321
|
+
...sessionFileLists(branch),
|
|
322
|
+
freeflow: {
|
|
323
|
+
version: 1,
|
|
324
|
+
cycle,
|
|
325
|
+
carried: [
|
|
326
|
+
...files.map((file) => fileRecord(file, cycle, previous)),
|
|
327
|
+
...results.map((result) => resultRecord(result, cycle, previous)),
|
|
328
|
+
...automatic.map((result) => ({ ...resultRecord(result, cycle, previous), automatic: true })),
|
|
329
|
+
],
|
|
330
|
+
files: cycleFiles(branch),
|
|
331
|
+
requestedBy,
|
|
332
|
+
...(this.host.routingProfile() ? { profile: this.host.routingProfile() } : {}),
|
|
333
|
+
...(this.host.routingAssignment() ? { assignment: this.host.routingAssignment() } : {}),
|
|
334
|
+
},
|
|
335
|
+
},
|
|
336
|
+
},
|
|
337
|
+
{
|
|
338
|
+
type: "custom_message",
|
|
339
|
+
customType: CARRIED_TYPE,
|
|
340
|
+
content: carriedText,
|
|
341
|
+
display: false,
|
|
342
|
+
// Under Cognitive Routing the Coordinator's projected view shows this version instead of the copies.
|
|
343
|
+
...(this.host.nativeRefs()
|
|
344
|
+
? {
|
|
345
|
+
details: {
|
|
346
|
+
coordinatorContent: renderCarriedForCoordinator(this.host.noticePrefix, cycle, userMessages, files, [
|
|
347
|
+
...results,
|
|
348
|
+
...automatic,
|
|
349
|
+
]),
|
|
350
|
+
},
|
|
351
|
+
}
|
|
352
|
+
: {}),
|
|
353
|
+
},
|
|
354
|
+
{ type: "custom_message", customType: RECOVERY_TYPE, content: recovery, display: true },
|
|
355
|
+
],
|
|
356
|
+
continue: true,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Pi is compacting on its own (its threshold, an overflow, or /compact). Freeflow keeps Pi's summarizer and kept
|
|
361
|
+
* tail, adds its summary instructions, and appends its own state with recovery steps. A scheduled Freeflow
|
|
362
|
+
* compaction is dropped: Pi's compaction replaces it. Returns undefined, so Pi compacts as usual, when compaction
|
|
363
|
+
* is off or anything fails; it never cancels Pi's compaction.
|
|
364
|
+
*/
|
|
365
|
+
async fallback(event, ctx) {
|
|
366
|
+
this.pending = undefined;
|
|
367
|
+
if (!this.host.effective()) return undefined;
|
|
368
|
+
try {
|
|
369
|
+
const branch = branchOf(ctx);
|
|
370
|
+
const cycle = nextCycle(branch);
|
|
371
|
+
const instructions = [FALLBACK_INSTRUCTIONS, event.customInstructions].filter(Boolean).join("\n\n");
|
|
372
|
+
// Pi merges the previous compaction's file lists only when Pi wrote it; add them back for Freeflow's.
|
|
373
|
+
const previousFiles = previousFileLists(branch);
|
|
374
|
+
const fileOps = event.preparation?.fileOps;
|
|
375
|
+
if (fileOps?.read && fileOps?.edited) {
|
|
376
|
+
for (const path of previousFiles.readFiles) fileOps.read.add(path);
|
|
377
|
+
for (const path of previousFiles.modifiedFiles) fileOps.edited.add(path);
|
|
378
|
+
}
|
|
379
|
+
const result = await this.host.summarize(event.preparation, instructions, event.signal, ctx);
|
|
380
|
+
if (!result?.summary) return undefined;
|
|
381
|
+
const summary = `${result.summary}\n\n${harnessPart({
|
|
382
|
+
cycle,
|
|
383
|
+
routingProfile: this.host.routingProfile(),
|
|
384
|
+
background: this.host.background(),
|
|
385
|
+
files: { readFiles: [], modifiedFiles: [] },
|
|
386
|
+
includeFiles: false,
|
|
387
|
+
listed: this.assignmentList(branch),
|
|
388
|
+
recovery: `${recoveryText(cycle)} ${AFTER_PI}`,
|
|
389
|
+
})}`;
|
|
390
|
+
this.requested = undefined;
|
|
391
|
+
return {
|
|
392
|
+
compaction: {
|
|
393
|
+
...result,
|
|
394
|
+
summary,
|
|
395
|
+
details: {
|
|
396
|
+
...(result.details ?? {}),
|
|
397
|
+
freeflow: { version: 1, cycle, fallback: true, carried: [] },
|
|
398
|
+
},
|
|
399
|
+
},
|
|
400
|
+
};
|
|
401
|
+
} catch {
|
|
402
|
+
// Pi's own compaction is the fallback's fallback.
|
|
403
|
+
return undefined;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
/** The compaction written at the last turn end, once; the caller then runs the post-compaction resets. */
|
|
407
|
+
takeCompacted() {
|
|
408
|
+
const compacted = this.compacted;
|
|
409
|
+
this.compacted = undefined;
|
|
410
|
+
return compacted;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
/** Freeflow's additions to Pi's own summarizer, written for a reader that summarizes someone else's conversation. */
|
|
414
|
+
const FALLBACK_INSTRUCTIONS = [
|
|
415
|
+
"Write state, not a story: what is true now, each item marked as settled, tentative, superseded, or unverified.",
|
|
416
|
+
"Keep exact paths, identifiers, commands, error text, numbers, and the user's words where wording matters; never paraphrase a decision or a constraint.",
|
|
417
|
+
"Never record a requested, reported, or expected result as observed. Name partial or uncommitted changes, unverified results, running commands, and obligations with what triggers each.",
|
|
418
|
+
"Say what the user has authorized and what still needs asking.",
|
|
419
|
+
"If the conversation uses a Working Record (.freeflow/tasks/*/record.md), name its path and do not restate what it holds; keep what it does not hold.",
|
|
420
|
+
].join(" ");
|
|
421
|
+
/**
|
|
422
|
+
* How to recover. Freeflow never names a Working Record here: it cannot tell which record belongs to this work, and
|
|
423
|
+
* pointing at the wrong one sends recovery into another task. The summary names the record when there is one.
|
|
424
|
+
*/
|
|
425
|
+
function recoveryText(cycle, carried = "") {
|
|
426
|
+
return `Compaction finished; cycle ${cycle} starts here. Recover before you continue: if the summary names a Working Record for this work, recover it as Track Work says; otherwise the summary is your record for this cycle, so re-read its Recovery sources. Reconcile with the live state your next step depends on, and verify work the summary calls done instead of redoing it. ${carried}This compaction is done, so do not re-read the compaction skill or its summary format. Then continue the work the compaction interrupted.`;
|
|
427
|
+
}
|
|
428
|
+
/** The agent path: the compaction was the request, and it is done. */
|
|
429
|
+
const AFTER_REQUESTED =
|
|
430
|
+
"This compaction completes the request for it: do not call freeflow_compact again in this cycle. If compacting was all you were asked to do, report that it is done (a worker returns its assignment with freeflow_return).";
|
|
431
|
+
/** Pi compacted on its own, so a Freeflow compaction being prepared is no longer needed. */
|
|
432
|
+
const AFTER_PI = "Compaction is no longer due: do not call freeflow_compact.";
|
|
433
|
+
/** Why freeflow_compact is refused when compaction is not due, and where to go next if a compaction began this cycle. */
|
|
434
|
+
function notDueText(branch) {
|
|
435
|
+
const latest = [...branch].reverse().find((entry) => entry?.type === "compaction");
|
|
436
|
+
const next =
|
|
437
|
+
"Continue the work; if this is a routing assignment that only asked for compaction, return it with freeflow_return.";
|
|
438
|
+
if (!latest)
|
|
439
|
+
return "Compaction is not due. Freeflow says when it is; the user can also ask for it with /freeflow compact.";
|
|
440
|
+
if (latest.details?.freeflow && !latest.details.freeflow.fallback)
|
|
441
|
+
return `Compaction is not due: this cycle began with a compaction, and that compaction completed any compaction your request or assignment asked for. ${next}`;
|
|
442
|
+
return `Compaction is not due: this cycle began with Pi's own compaction, so the compaction you were preparing is no longer needed. ${next}`;
|
|
443
|
+
}
|
|
444
|
+
/** What the previous Freeflow compaction carried (file paths and result ids), with the cycle each was first carried. */
|
|
445
|
+
function previousCarried(branch) {
|
|
446
|
+
const latest = [...branch].reverse().find((entry) => entry?.type === "compaction" && entry.details?.freeflow);
|
|
447
|
+
const carried = new Map();
|
|
448
|
+
for (const item of latest?.details?.freeflow?.carried ?? []) {
|
|
449
|
+
const key = item?.kind === "file" ? item.path : item?.kind === "result" ? item.ref : undefined;
|
|
450
|
+
if (typeof key === "string") carried.set(`${item.kind}:${key}`, item.firstCycle);
|
|
451
|
+
}
|
|
452
|
+
return carried;
|
|
453
|
+
}
|
|
454
|
+
function fileRecord(file, cycle, previous) {
|
|
455
|
+
return {
|
|
456
|
+
kind: "file",
|
|
457
|
+
path: file.path,
|
|
458
|
+
...("lines" in file && file.lines ? { lines: file.lines } : {}),
|
|
459
|
+
firstCycle: previous.get(`file:${file.path}`) ?? cycle,
|
|
460
|
+
...("text" in file ? { bodyHash: hash(file.text) } : { error: file.error }),
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
function resultRecord(result, cycle, previous) {
|
|
464
|
+
return {
|
|
465
|
+
kind: "result",
|
|
466
|
+
ref: result.id,
|
|
467
|
+
tool: result.tool,
|
|
468
|
+
firstCycle: previous.get(`result:${result.id}`) ?? cycle,
|
|
469
|
+
bodyHash: hash(result.text),
|
|
470
|
+
};
|
|
471
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { touchedPaths } from "../tool-execution/file-state.js";
|
|
2
|
+
/** Entries after the latest compaction on the branch: the current cycle. */
|
|
3
|
+
export function currentCycle(branch) {
|
|
4
|
+
let start = 0;
|
|
5
|
+
branch.forEach((entry, i) => {
|
|
6
|
+
if (entry?.type === "compaction") start = i + 1;
|
|
7
|
+
});
|
|
8
|
+
return branch.slice(start);
|
|
9
|
+
}
|
|
10
|
+
/** The cycle number the next compaction starts. Cycle 1 runs from session start to the first compaction. */
|
|
11
|
+
export const nextCycle = (branch) => branch.filter((entry) => entry?.type === "compaction").length + 2;
|
|
12
|
+
/**
|
|
13
|
+
* Files successful calls in this cycle read or changed, in first-touched order. Calls a codemode script made count
|
|
14
|
+
* too: Pi records them on the script's result as nested calls.
|
|
15
|
+
*/
|
|
16
|
+
export function cycleFiles(branch) {
|
|
17
|
+
const calls = new Map();
|
|
18
|
+
const read = new Set(),
|
|
19
|
+
changed = new Set();
|
|
20
|
+
const touch = (name, input) => {
|
|
21
|
+
for (const path of touchedPaths(name, input)) (name === "read" ? read : changed).add(path);
|
|
22
|
+
};
|
|
23
|
+
for (const entry of currentCycle(branch)) {
|
|
24
|
+
const message = entry?.type === "message" ? entry.message : undefined;
|
|
25
|
+
if (message?.role === "assistant")
|
|
26
|
+
for (const block of message.content ?? [])
|
|
27
|
+
if (block?.type === "toolCall") calls.set(block.id, { name: block.name, input: block.arguments });
|
|
28
|
+
if (message?.role !== "toolResult") continue;
|
|
29
|
+
for (const nested of message.nestedCalls?.calls ?? [])
|
|
30
|
+
if (nested?.status === "ok") touch(nested.name, nested.arguments);
|
|
31
|
+
const call = calls.get(message.toolCallId);
|
|
32
|
+
if (call && message.isError !== true) touch(call.name, call.input);
|
|
33
|
+
}
|
|
34
|
+
return { read: [...read].filter((path) => !changed.has(path)), changed: [...changed] };
|
|
35
|
+
}
|
|
36
|
+
/** The file lists the latest compaction stored in Pi's details format, whoever wrote it. */
|
|
37
|
+
export function previousFileLists(branch) {
|
|
38
|
+
const latest = [...branch].reverse().find((entry) => entry?.type === "compaction");
|
|
39
|
+
const strings = (value) => (Array.isArray(value) ? value.filter((v) => typeof v === "string") : []);
|
|
40
|
+
return { readFiles: strings(latest?.details?.readFiles), modifiedFiles: strings(latest?.details?.modifiedFiles) };
|
|
41
|
+
}
|
|
42
|
+
/** Session-wide lists in Pi's format: earlier compactions' lists plus this cycle; a modified file is not "read". */
|
|
43
|
+
export function sessionFileLists(branch) {
|
|
44
|
+
const previous = previousFileLists(branch);
|
|
45
|
+
const cycle = cycleFiles(branch);
|
|
46
|
+
const modified = new Set([...previous.modifiedFiles, ...cycle.changed]);
|
|
47
|
+
const read = new Set([...previous.readFiles, ...cycle.read].filter((path) => !modified.has(path)));
|
|
48
|
+
return { readFiles: [...read].sort(), modifiedFiles: [...modified].sort() };
|
|
49
|
+
}
|
|
50
|
+
/** Pi's own file-list form, so summaries read alike whichever path wrote them. */
|
|
51
|
+
export function formatFileLists(lists) {
|
|
52
|
+
return [
|
|
53
|
+
lists.readFiles.length ? `<read-files>\n${lists.readFiles.join("\n")}\n</read-files>` : "",
|
|
54
|
+
lists.modifiedFiles.length ? `<modified-files>\n${lists.modifiedFiles.join("\n")}\n</modified-files>` : "",
|
|
55
|
+
]
|
|
56
|
+
.filter(Boolean)
|
|
57
|
+
.join("\n\n");
|
|
58
|
+
}
|
|
59
|
+
export function harnessPart(facts) {
|
|
60
|
+
const requested =
|
|
61
|
+
facts.requestedBy === "user"
|
|
62
|
+
? " It completes the compaction the user asked for with /freeflow compact."
|
|
63
|
+
: facts.requestedBy === "notice"
|
|
64
|
+
? " It completes the compaction Freeflow's context notice asked for."
|
|
65
|
+
: "";
|
|
66
|
+
const lines = [`## Freeflow state at compaction`, "", `This compaction starts cycle ${facts.cycle}.${requested}`];
|
|
67
|
+
if (facts.routingProfile) lines.push(`Cognitive Routing profile when compacted: ${facts.routingProfile}.`);
|
|
68
|
+
if (facts.background.length)
|
|
69
|
+
lines.push(
|
|
70
|
+
`Background commands still running: ${facts.background.map((job) => `${job.id} (${job.label}), output ${job.outputPath}`).join("; ")}.`,
|
|
71
|
+
);
|
|
72
|
+
const files = facts.includeFiles === false ? "" : formatFileLists(facts.files);
|
|
73
|
+
if (files) lines.push("", "Files read and modified in this session:", "", files);
|
|
74
|
+
if (facts.listed) lines.push("", facts.listed.replace(/^## /, "### "));
|
|
75
|
+
if (facts.recovery) lines.push("", facts.recovery);
|
|
76
|
+
return lines.join("\n");
|
|
77
|
+
}
|