diffpilot 0.0.1__py3-none-any.whl
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.
- diffpilot/__init__.py +11 -0
- diffpilot/__init__.pyi +3 -0
- diffpilot/__main__.py +3 -0
- diffpilot/__main__.pyi +1 -0
- diffpilot/agents.py +438 -0
- diffpilot/agents.pyi +81 -0
- diffpilot/agentsmd.py +97 -0
- diffpilot/agentsmd.pyi +12 -0
- diffpilot/bootstrap.py +456 -0
- diffpilot/bootstrap.pyi +49 -0
- diffpilot/cli.py +731 -0
- diffpilot/cli.pyi +62 -0
- diffpilot/config.py +342 -0
- diffpilot/config.pyi +109 -0
- diffpilot/core.py +333 -0
- diffpilot/core.pyi +26 -0
- diffpilot/events.py +172 -0
- diffpilot/events.pyi +28 -0
- diffpilot/gitdiff.py +170 -0
- diffpilot/gitdiff.pyi +14 -0
- diffpilot/index.py +242 -0
- diffpilot/index.pyi +60 -0
- diffpilot/jev.py +203 -0
- diffpilot/jev.pyi +33 -0
- diffpilot/llm.py +141 -0
- diffpilot/llm.pyi +28 -0
- diffpilot/ops.py +285 -0
- diffpilot/ops.pyi +31 -0
- diffpilot/prompts.py +432 -0
- diffpilot/prompts.pyi +28 -0
- diffpilot/py.typed +0 -0
- diffpilot/schemas.py +110 -0
- diffpilot/schemas.pyi +88 -0
- diffpilot/store.py +315 -0
- diffpilot/store.pyi +43 -0
- diffpilot/verify.py +352 -0
- diffpilot/verify.pyi +58 -0
- diffpilot-0.0.1.dist-info/METADATA +80 -0
- diffpilot-0.0.1.dist-info/RECORD +42 -0
- diffpilot-0.0.1.dist-info/WHEEL +5 -0
- diffpilot-0.0.1.dist-info/entry_points.txt +2 -0
- diffpilot-0.0.1.dist-info/top_level.txt +1 -0
diffpilot/jev.pyi
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from _typeshed import Incomplete
|
|
2
|
+
from diffpilot.config import Config as Config
|
|
3
|
+
from diffpilot.index import Index as Index
|
|
4
|
+
from diffpilot.store import clip as clip
|
|
5
|
+
from pydantic import BaseModel as BaseModel
|
|
6
|
+
from pydantic_ai.models import Model as Model
|
|
7
|
+
|
|
8
|
+
log: Incomplete
|
|
9
|
+
OPENROUTER_BASE: str
|
|
10
|
+
SECTION_CHARS: int
|
|
11
|
+
EVIDENCE_CHARS: int
|
|
12
|
+
POOL: int
|
|
13
|
+
CHUNK_CHARS: int
|
|
14
|
+
PARALLEL: int
|
|
15
|
+
SCOPES: Incomplete
|
|
16
|
+
|
|
17
|
+
class Jev:
|
|
18
|
+
cfg: Incomplete
|
|
19
|
+
calls: int
|
|
20
|
+
model: Model | None
|
|
21
|
+
def __init__(self, cfg: Config) -> None: ...
|
|
22
|
+
@property
|
|
23
|
+
def available(self) -> bool: ...
|
|
24
|
+
async def probabilities(self, state: str, questions: dict[str, str]) -> dict[str, float] | None: ...
|
|
25
|
+
async def relevance(self, request: str, candidates: dict[str, str]) -> dict[str, float] | None: ...
|
|
26
|
+
async def route(self, text: str, scopes: dict[str, str]) -> dict[str, float] | None: ...
|
|
27
|
+
|
|
28
|
+
async def rank(j: Jev | None, idx: Index, query: str, limit: int, stores: tuple[str, ...], threshold: float) -> list[tuple[str, float]]: ...
|
|
29
|
+
async def chunk_value(j: Jev | None, chunks: dict[str, str]) -> dict[str, float] | None: ...
|
|
30
|
+
async def covered(j: Jev | None, idx: Index, facts: list[str], stores: tuple[str, ...]) -> list[float] | None: ...
|
|
31
|
+
async def stated(j: Jev | None, facts: list[tuple[str, str]]) -> list[float] | None: ...
|
|
32
|
+
def scopes(cfg: Config, stores: tuple[str, ...]) -> dict[str, str]: ...
|
|
33
|
+
async def routing_hint(j: Jev | None, cfg: Config, text: str, stores: tuple[str, ...]) -> str: ...
|
diffpilot/llm.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""LLM engine: Pydantic AI on the Codex (ChatGPT subscription) or OpenRouter backend, plus Jev for fast decisions."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Self, cast
|
|
7
|
+
|
|
8
|
+
from pydantic_ai import Agent
|
|
9
|
+
from pydantic_ai.exceptions import (
|
|
10
|
+
ModelAPIError,
|
|
11
|
+
ModelHTTPError,
|
|
12
|
+
UnexpectedModelBehavior,
|
|
13
|
+
UsageLimitExceeded,
|
|
14
|
+
UserError,
|
|
15
|
+
)
|
|
16
|
+
from pydantic_ai.models import Model
|
|
17
|
+
from pydantic_ai.models.openai_codex import OpenAICodexModel
|
|
18
|
+
from pydantic_ai.models.openrouter import OpenRouterModel
|
|
19
|
+
from pydantic_ai.providers.openai_codex import OpenAICodexCredentials, OpenAICodexProvider
|
|
20
|
+
from pydantic_ai.providers.openrouter import OpenRouterProvider
|
|
21
|
+
from pydantic_ai.usage import RunUsage, UsageLimits
|
|
22
|
+
|
|
23
|
+
from diffpilot import events
|
|
24
|
+
from diffpilot.config import Config, DPError
|
|
25
|
+
from diffpilot.index import now
|
|
26
|
+
from diffpilot.jev import Jev
|
|
27
|
+
|
|
28
|
+
log = logging.getLogger('diffpilot')
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Engine:
|
|
32
|
+
"""One per diffpilot command: credentials, models, Jev, usage accounting. Use as `async with`."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, cfg: Config, command: str) -> None:
|
|
35
|
+
self.cfg = cfg
|
|
36
|
+
self.command = command
|
|
37
|
+
self.usage = RunUsage()
|
|
38
|
+
self.started = time.monotonic()
|
|
39
|
+
self.jev = Jev(cfg)
|
|
40
|
+
self._provider: OpenAICodexProvider | None = None
|
|
41
|
+
self._models: dict[bool, Model] = {}
|
|
42
|
+
self.trace_path = cfg.state / 'runs' / f'{now().replace(":", "")}-{command}.jsonl'
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def backend(self) -> str:
|
|
46
|
+
"""Resolve [llm].backend: auto = Codex subscription when logged in, else OpenRouter."""
|
|
47
|
+
b = self.cfg.llm.backend
|
|
48
|
+
if b == 'auto':
|
|
49
|
+
has_codex = (self.cfg.codex_home / 'auth.json').exists()
|
|
50
|
+
return 'codex' if has_codex or not self.cfg.openrouter_key else 'openrouter'
|
|
51
|
+
if b not in ('codex', 'openrouter'):
|
|
52
|
+
raise DPError(f'[llm].backend must be auto, codex or openrouter, got {b!r}')
|
|
53
|
+
return b
|
|
54
|
+
|
|
55
|
+
def provider(self) -> OpenAICodexProvider:
|
|
56
|
+
if self._provider is None:
|
|
57
|
+
path = self.cfg.codex_home / 'auth.json'
|
|
58
|
+
if not path.exists():
|
|
59
|
+
raise DPError(f'Codex auth not found at {path}. Run `codex login`, or set [auth].codex_home.', 2)
|
|
60
|
+
try:
|
|
61
|
+
creds = OpenAICodexCredentials.from_codex_cli_auth(json.loads(path.read_text(encoding='utf-8')))
|
|
62
|
+
except Exception as e: # noqa: BLE001 - malformed auth file
|
|
63
|
+
raise DPError(f'cannot read Codex credentials from {path}: {e}', 2) from e
|
|
64
|
+
self._provider = OpenAICodexProvider(credentials=creds) # read-only: refreshed tokens stay in memory
|
|
65
|
+
return self._provider
|
|
66
|
+
|
|
67
|
+
def model(self, fast: bool = False) -> Model:
|
|
68
|
+
if fast not in self._models:
|
|
69
|
+
llm = self.cfg.llm
|
|
70
|
+
name = (llm.fast_model if fast else '') or llm.model
|
|
71
|
+
effort = llm.fast_reasoning if fast else llm.reasoning
|
|
72
|
+
if self.backend == 'openrouter':
|
|
73
|
+
if not self.cfg.openrouter_key:
|
|
74
|
+
raise DPError('OpenRouter backend needs $OPENROUTER_API_KEY or [auth].openrouter_api_key.', 2)
|
|
75
|
+
try:
|
|
76
|
+
self._models[fast] = OpenRouterModel(
|
|
77
|
+
name,
|
|
78
|
+
provider=OpenRouterProvider(api_key=self.cfg.openrouter_key),
|
|
79
|
+
settings=cast(Any, {'openrouter_reasoning': {'effort': effort}, 'timeout': llm.timeout_s}),
|
|
80
|
+
)
|
|
81
|
+
except UserError as e: # e.g. model id without the "vendor/" prefix
|
|
82
|
+
raise DPError(f'{e} Set [llm].model / fast_model for the OpenRouter backend.') from e
|
|
83
|
+
return self._models[fast]
|
|
84
|
+
self._models[fast] = OpenAICodexModel(
|
|
85
|
+
name,
|
|
86
|
+
provider=self.provider(),
|
|
87
|
+
settings=cast(
|
|
88
|
+
Any,
|
|
89
|
+
{
|
|
90
|
+
'openai_reasoning_effort': effort,
|
|
91
|
+
'timeout': llm.timeout_s,
|
|
92
|
+
},
|
|
93
|
+
),
|
|
94
|
+
)
|
|
95
|
+
return self._models[fast]
|
|
96
|
+
|
|
97
|
+
async def run[T](self, agent: Agent[Any, T], prompt: str, deps: Any = None, fast: bool = False) -> T:
|
|
98
|
+
try:
|
|
99
|
+
res = await agent.run(
|
|
100
|
+
prompt,
|
|
101
|
+
model=self.model(fast),
|
|
102
|
+
deps=deps,
|
|
103
|
+
usage_limits=UsageLimits(request_limit=self.cfg.llm.max_requests),
|
|
104
|
+
)
|
|
105
|
+
except DPError:
|
|
106
|
+
raise
|
|
107
|
+
except UsageLimitExceeded as e:
|
|
108
|
+
raise DPError(f'agent exceeded its request budget ([llm].max_requests): {e}', 3) from e
|
|
109
|
+
except UnexpectedModelBehavior as e:
|
|
110
|
+
raise DPError(f'model did not produce a valid result: {e}', 4) from e
|
|
111
|
+
except ModelHTTPError as e:
|
|
112
|
+
raise DPError(
|
|
113
|
+
f'{self.backend} backend error {e.status_code}: {e.message}', 2 if e.status_code in (401, 403) else 3
|
|
114
|
+
) from e
|
|
115
|
+
except ModelAPIError as e:
|
|
116
|
+
raise DPError(f'{self.backend} backend error: {e}', 3) from e
|
|
117
|
+
self.usage = self.usage + res.usage
|
|
118
|
+
if self.cfg.logging.trace:
|
|
119
|
+
self.trace_path.parent.mkdir(parents=True, exist_ok=True)
|
|
120
|
+
with self.trace_path.open('ab') as f:
|
|
121
|
+
f.write(res.all_messages_json() + b'\n')
|
|
122
|
+
return res.output
|
|
123
|
+
|
|
124
|
+
def usage_dict(self) -> dict:
|
|
125
|
+
u = self.usage
|
|
126
|
+
return {
|
|
127
|
+
'requests': u.requests,
|
|
128
|
+
'tool_calls': u.tool_calls,
|
|
129
|
+
'input': u.input_tokens,
|
|
130
|
+
'cached': u.cache_read_tokens,
|
|
131
|
+
'output': u.output_tokens,
|
|
132
|
+
'jev_calls': self.jev.calls,
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async def __aenter__(self) -> Self:
|
|
136
|
+
return self
|
|
137
|
+
|
|
138
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
139
|
+
if self.usage.requests or self.jev.calls:
|
|
140
|
+
ms = int((time.monotonic() - self.started) * 1000)
|
|
141
|
+
events.log_run(self.cfg, {'ts': now(), 'command': self.command, **self.usage_dict(), 'ms': ms})
|
diffpilot/llm.pyi
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from _typeshed import Incomplete
|
|
2
|
+
from diffpilot import events as events
|
|
3
|
+
from diffpilot.config import Config as Config, DPError as DPError
|
|
4
|
+
from diffpilot.index import now as now
|
|
5
|
+
from diffpilot.jev import Jev as Jev
|
|
6
|
+
from pydantic_ai import Agent as Agent
|
|
7
|
+
from pydantic_ai.models import Model as Model
|
|
8
|
+
from pydantic_ai.providers.openai_codex import OpenAICodexProvider
|
|
9
|
+
from typing import Any, Self
|
|
10
|
+
|
|
11
|
+
log: Incomplete
|
|
12
|
+
|
|
13
|
+
class Engine:
|
|
14
|
+
cfg: Incomplete
|
|
15
|
+
command: Incomplete
|
|
16
|
+
usage: Incomplete
|
|
17
|
+
started: Incomplete
|
|
18
|
+
jev: Incomplete
|
|
19
|
+
trace_path: Incomplete
|
|
20
|
+
def __init__(self, cfg: Config, command: str) -> None: ...
|
|
21
|
+
@property
|
|
22
|
+
def backend(self) -> str: ...
|
|
23
|
+
def provider(self) -> OpenAICodexProvider: ...
|
|
24
|
+
def model(self, fast: bool = False) -> Model: ...
|
|
25
|
+
async def run[T](self, agent: Agent[Any, T], prompt: str, deps: Any = None, fast: bool = False) -> T: ...
|
|
26
|
+
def usage_dict(self) -> dict: ...
|
|
27
|
+
async def __aenter__(self) -> Self: ...
|
|
28
|
+
async def __aexit__(self, *exc: object) -> None: ...
|
diffpilot/ops.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""Validated, deterministic store writes: edit-op planning, diff preview, apply under the lock, manual-edit sync."""
|
|
2
|
+
|
|
3
|
+
import difflib
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from diffpilot import events, prompts, store
|
|
8
|
+
from diffpilot.config import Config, DPError
|
|
9
|
+
from diffpilot.events import git_head
|
|
10
|
+
from diffpilot.index import Index, Locked, now
|
|
11
|
+
from diffpilot.schemas import EditOp
|
|
12
|
+
from diffpilot.store import clip
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def open_index(cfg: Config) -> Index:
|
|
16
|
+
"""Load the index and record manual edits made since the last sync."""
|
|
17
|
+
idx = Index(cfg)
|
|
18
|
+
with Locked(cfg):
|
|
19
|
+
sync_manual(cfg, idx)
|
|
20
|
+
return idx
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def sync_manual(cfg: Config, idx: Index) -> None:
|
|
24
|
+
idx.data = Index(cfg).data
|
|
25
|
+
res = idx.sync()
|
|
26
|
+
if res.any and idx.meta.get('synced'):
|
|
27
|
+
ops = [
|
|
28
|
+
{'op': k, 'ref': r}
|
|
29
|
+
for k, refs in (('added', res.added), ('changed', res.changed), ('removed', res.removed))
|
|
30
|
+
for r in refs
|
|
31
|
+
]
|
|
32
|
+
events.append(
|
|
33
|
+
cfg,
|
|
34
|
+
{
|
|
35
|
+
'id': events.new_id(),
|
|
36
|
+
'ts': now(),
|
|
37
|
+
'command': 'manual',
|
|
38
|
+
'ops': ops,
|
|
39
|
+
'summary': f'Manual edit of {len(ops)} section(s)',
|
|
40
|
+
'changelog': False,
|
|
41
|
+
'released': False,
|
|
42
|
+
},
|
|
43
|
+
)
|
|
44
|
+
idx.meta['synced'] = True
|
|
45
|
+
idx.save()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class Applied:
|
|
50
|
+
lines: list[str] = field(default_factory=list)
|
|
51
|
+
ops: list[dict] = field(default_factory=list)
|
|
52
|
+
warnings: list[str] = field(default_factory=list)
|
|
53
|
+
refs: list[str] = field(default_factory=list)
|
|
54
|
+
event_id: str | None = None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class Plan:
|
|
59
|
+
texts: dict[str, str]
|
|
60
|
+
orig: dict[str, str]
|
|
61
|
+
ops: list[dict] = field(default_factory=list)
|
|
62
|
+
warnings: list[str] = field(default_factory=list)
|
|
63
|
+
links: list[tuple[str, str]] = field(default_factory=list)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def plan_ops( # noqa: C901 - one linear validation pass per op type
|
|
67
|
+
cfg: Config,
|
|
68
|
+
idx: Index,
|
|
69
|
+
ops: list[EditOp],
|
|
70
|
+
shown: dict[str, str],
|
|
71
|
+
allowed: tuple[str, ...],
|
|
72
|
+
owner_only: bool = False,
|
|
73
|
+
strict: bool = True,
|
|
74
|
+
) -> Plan:
|
|
75
|
+
"""Validate ops and compute the new store texts in memory (nothing is written)."""
|
|
76
|
+
texts = {st: cfg.store_path(st).read_text(encoding='utf-8') for st in allowed if cfg.store_path(st).exists()}
|
|
77
|
+
plan = Plan(texts=texts, orig=dict(texts))
|
|
78
|
+
for n, op in enumerate(ops):
|
|
79
|
+
before = len(plan.ops)
|
|
80
|
+
st, _, sid = op.target.partition(':')
|
|
81
|
+
sid = sid.strip()
|
|
82
|
+
if st not in allowed or st not in texts:
|
|
83
|
+
plan.warnings.append(f'skipped {op.op} on {op.target}: store not allowed for this command')
|
|
84
|
+
continue
|
|
85
|
+
view = idx.views.get(op.target)
|
|
86
|
+
try:
|
|
87
|
+
if op.op in ('replace', 'append', 'delete'):
|
|
88
|
+
if view is None:
|
|
89
|
+
plan.warnings.append(f'skipped {op.op}: {op.target} does not exist')
|
|
90
|
+
continue
|
|
91
|
+
if op.target not in shown:
|
|
92
|
+
plan.warnings.append(f'skipped {op.op} on {op.target}: section was not read first (use show)')
|
|
93
|
+
continue
|
|
94
|
+
if shown[op.target] != view.hash:
|
|
95
|
+
if strict:
|
|
96
|
+
raise DPError(f'{op.target} changed while diffpilot was working; re-run the command', 4)
|
|
97
|
+
plan.warnings.append(f'{op.target} changed since it was shown; show it again')
|
|
98
|
+
continue
|
|
99
|
+
# bootstrap may add details anywhere, but only rewrites or removes what it wrote itself
|
|
100
|
+
if owner_only and op.op != 'append' and idx.sections[op.target].get('origin') != 'bootstrap':
|
|
101
|
+
plan.warnings.append(f'conflict (not written): {op.target} is not bootstrap-owned')
|
|
102
|
+
continue
|
|
103
|
+
if op.op == 'replace':
|
|
104
|
+
if (op.text or '').strip() == view.body.strip() and not op.heading: # type: ignore[union-attr]
|
|
105
|
+
continue
|
|
106
|
+
texts[st] = store.op_replace(texts[st], sid, op.text or '', op.heading)
|
|
107
|
+
plan.ops.append({'op': 'replace', 'target': op.target, 'before': view.body, 'after': op.text}) # type: ignore[union-attr]
|
|
108
|
+
elif op.op == 'append':
|
|
109
|
+
if rep := _repeated(view.body, op.text or ''): # type: ignore[union-attr]
|
|
110
|
+
plan.warnings.append(
|
|
111
|
+
f'append to {op.target} repeats an existing paragraph ("{clip(rep, 120)}"): append only the '
|
|
112
|
+
'new details, or replace the section with one merged body'
|
|
113
|
+
)
|
|
114
|
+
texts[st] = store.op_append(texts[st], sid, op.text or '')
|
|
115
|
+
plan.ops.append({'op': 'append', 'target': op.target, 'after': op.text})
|
|
116
|
+
elif op.op == 'delete':
|
|
117
|
+
texts[st] = store.op_delete(texts[st], sid)
|
|
118
|
+
plan.ops.append({'op': 'delete', 'target': op.target, 'before': view.body, 'ref': op.target}) # type: ignore[union-attr]
|
|
119
|
+
elif op.op == 'add':
|
|
120
|
+
if not (op.heading or '').strip():
|
|
121
|
+
plan.warnings.append(f'skipped add under {op.target}: no heading')
|
|
122
|
+
continue
|
|
123
|
+
dup = _duplicate(idx, st, op.text or '')
|
|
124
|
+
if dup:
|
|
125
|
+
plan.warnings.append(f'skipped add "{op.heading}": duplicates {dup}')
|
|
126
|
+
continue
|
|
127
|
+
texts[st] = store.op_add(texts[st], sid or None, op.heading or '', op.text or '')
|
|
128
|
+
plan.ops.append({'op': 'add', 'target': op.target, 'heading': op.heading, 'after': op.text})
|
|
129
|
+
elif op.op == 'link':
|
|
130
|
+
if op.target in idx.views and op.link_to in idx.views:
|
|
131
|
+
if op.link_to not in idx.sections[op.target].get('links', []):
|
|
132
|
+
plan.links.append((op.target, op.link_to))
|
|
133
|
+
plan.ops.append({'op': 'link', 'target': op.target, 'link_to': op.link_to})
|
|
134
|
+
else:
|
|
135
|
+
plan.warnings.append(f'skipped link {op.target} → {op.link_to}: unknown ref')
|
|
136
|
+
except KeyError:
|
|
137
|
+
plan.warnings.append(f'skipped {op.op}: {op.target} not found (removed by an earlier op?)')
|
|
138
|
+
if len(plan.ops) > before:
|
|
139
|
+
plan.ops[-1]['n'] = n
|
|
140
|
+
for st, text in texts.items():
|
|
141
|
+
if text != plan.orig[st]:
|
|
142
|
+
texts[st] = store.ensure_ids(store.normalize(text))[0]
|
|
143
|
+
return plan
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def preview(cfg: Config, plan: Plan, budget_chars: int) -> str:
|
|
147
|
+
"""Unified diff of what the plan would write."""
|
|
148
|
+
parts = []
|
|
149
|
+
for st, text in plan.texts.items():
|
|
150
|
+
if text != plan.orig[st]:
|
|
151
|
+
name = cfg.rel(cfg.store_path(st))
|
|
152
|
+
diff = difflib.unified_diff(
|
|
153
|
+
plan.orig[st].splitlines(), text.splitlines(), f'a/{name}', f'b/{name}', n=2, lineterm=''
|
|
154
|
+
)
|
|
155
|
+
parts.append('\n'.join(diff))
|
|
156
|
+
parts += [f'link {o["target"]} → {o["link_to"]}' for o in plan.ops if o['op'] == 'link']
|
|
157
|
+
text = '\n'.join(parts) or '(no changes would be written)'
|
|
158
|
+
return text if len(text) <= budget_chars else text[:budget_chars] + '\n… (diff truncated)'
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def apply_ops(
|
|
162
|
+
cfg: Config,
|
|
163
|
+
idx: Index,
|
|
164
|
+
ops: list[EditOp],
|
|
165
|
+
shown: dict[str, str],
|
|
166
|
+
origin: str,
|
|
167
|
+
allowed: tuple[str, ...],
|
|
168
|
+
event: dict,
|
|
169
|
+
owner_only: bool = False,
|
|
170
|
+
files: list[str] | None = None,
|
|
171
|
+
) -> Applied:
|
|
172
|
+
"""Validate and apply model ops under the lock; write the change event. Raises DPError(4) on stale reads."""
|
|
173
|
+
out = Applied()
|
|
174
|
+
with Locked(cfg):
|
|
175
|
+
sync_manual(cfg, idx)
|
|
176
|
+
plan = plan_ops(cfg, idx, ops, shown, allowed, owner_only)
|
|
177
|
+
out.ops, out.warnings = plan.ops, plan.warnings
|
|
178
|
+
for st, text in plan.texts.items():
|
|
179
|
+
if text != plan.orig[st]:
|
|
180
|
+
store.atomic_write(cfg.store_path(st), text)
|
|
181
|
+
for src, dst in plan.links:
|
|
182
|
+
idx.sections[src].setdefault('links', []).append(dst)
|
|
183
|
+
if not out.ops:
|
|
184
|
+
idx.save()
|
|
185
|
+
return out
|
|
186
|
+
eid = events.new_id()
|
|
187
|
+
res = idx.sync(origin=origin, change=eid)
|
|
188
|
+
for o in out.ops:
|
|
189
|
+
if o['op'] == 'add':
|
|
190
|
+
heading = o.get('heading', '').strip()
|
|
191
|
+
match = [
|
|
192
|
+
r for r in res.added if idx.views[r].heading == heading and r.startswith(o['target'].split(':')[0])
|
|
193
|
+
]
|
|
194
|
+
o['ref'] = match[0] if match else None
|
|
195
|
+
else:
|
|
196
|
+
o.setdefault('ref', o['target'])
|
|
197
|
+
out.refs = list(res.added + res.changed)
|
|
198
|
+
for r in out.refs:
|
|
199
|
+
e = idx.sections[r]
|
|
200
|
+
e['code_refs'] = sorted(set(e.get('code_refs', [])) | set(files or []))
|
|
201
|
+
idx.save()
|
|
202
|
+
for o in out.ops:
|
|
203
|
+
verb = {'replace': 'Updated', 'append': 'Extended', 'add': 'Added', 'delete': 'Deleted', 'link': 'Linked'}[
|
|
204
|
+
o['op']
|
|
205
|
+
]
|
|
206
|
+
ref = o.get('ref') or o['target']
|
|
207
|
+
label = f'{ref} → {o["link_to"]}' if o['op'] == 'link' else ref
|
|
208
|
+
out.lines.append(f'{verb:<8} {label}')
|
|
209
|
+
event.update(
|
|
210
|
+
id=eid, ts=now(), ops=out.ops, git_head=git_head(cfg), released=False, prompt_version=prompts.PROMPT_VERSION
|
|
211
|
+
)
|
|
212
|
+
events.append(cfg, event)
|
|
213
|
+
if event.get('changelog', True):
|
|
214
|
+
events.refresh_unreleased(cfg)
|
|
215
|
+
out.event_id = eid
|
|
216
|
+
return out
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _repeated(body: str, text: str, ratio: float = 0.6) -> str | None:
|
|
220
|
+
"""Return the existing paragraph that an appended paragraph restates, if any."""
|
|
221
|
+
old = [p for p in body.split('\n\n') if len(p.strip()) > 60]
|
|
222
|
+
for new in (p for p in text.split('\n\n') if len(p.strip()) > 60):
|
|
223
|
+
for p in old:
|
|
224
|
+
if difflib.SequenceMatcher(None, clip(p, 1500), clip(new, 1500)).ratio() > ratio:
|
|
225
|
+
return p
|
|
226
|
+
return None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _duplicate(idx: Index, st: str, text: str) -> str | None:
|
|
230
|
+
norm = clip(text, 2000).lower()
|
|
231
|
+
if len(norm) < 30:
|
|
232
|
+
return None
|
|
233
|
+
for ref, v in idx.views.items():
|
|
234
|
+
if v.store == st and difflib.SequenceMatcher(None, norm, clip(v.body, 2000).lower()).ratio() > 0.9:
|
|
235
|
+
return ref
|
|
236
|
+
return None
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def import_doc(cfg: Config, rel: str, target: str) -> dict:
|
|
240
|
+
"""Move a document verbatim into a store (`store` or `store:parent-id`) as one section with its subsections.
|
|
241
|
+
|
|
242
|
+
No LLM: the text and heading names are kept, headings are demoted under the target, dp:id anchors are regenerated.
|
|
243
|
+
The source file is left in place (diffpilot writes only its stores); delete it once `show` looks right.
|
|
244
|
+
"""
|
|
245
|
+
st, _, parent = target.partition(':')
|
|
246
|
+
if st not in cfg.stores:
|
|
247
|
+
raise DPError(f'unknown store {st!r}; stores: {", ".join(cfg.stores)}')
|
|
248
|
+
src = cfg.root / rel
|
|
249
|
+
if Path(rel).is_absolute() or not src.is_file() or cfg.is_own(rel):
|
|
250
|
+
raise DPError(f'{rel}: not a project document outside the stores')
|
|
251
|
+
text = src.read_text(encoding='utf-8')
|
|
252
|
+
lines = text.split('\n')
|
|
253
|
+
heads = [s for s in store.parse(text) if s.level == 1]
|
|
254
|
+
if len(heads) == 1 and not ''.join(lines[: heads[0].start]).strip(): # the file's own title
|
|
255
|
+
heading, body = heads[0].heading, '\n'.join(lines[heads[0].start + 1 :])
|
|
256
|
+
else:
|
|
257
|
+
heading, body = src.stem.replace('_', ' ').replace('-', ' ').capitalize(), text
|
|
258
|
+
path = cfg.store_path(st)
|
|
259
|
+
idx = Index(cfg)
|
|
260
|
+
with Locked(cfg):
|
|
261
|
+
sync_manual(cfg, idx)
|
|
262
|
+
if parent and f'{st}:{parent}' not in idx.views:
|
|
263
|
+
raise DPError(f'{target}: no such section')
|
|
264
|
+
old = path.read_text(encoding='utf-8') if path.exists() else f'# {cfg.store_title(st)}\n'
|
|
265
|
+
store.atomic_write(path, store.op_add(old, parent or None, heading, body))
|
|
266
|
+
eid = events.new_id()
|
|
267
|
+
res = idx.sync(origin='import', change=eid)
|
|
268
|
+
events.append(
|
|
269
|
+
cfg,
|
|
270
|
+
{
|
|
271
|
+
'id': eid,
|
|
272
|
+
'ts': now(),
|
|
273
|
+
'command': 'import',
|
|
274
|
+
'ops': [{'op': 'add', 'ref': r} for r in res.added],
|
|
275
|
+
'summary': f'Imported {rel} verbatim into {target}',
|
|
276
|
+
'changelog': False,
|
|
277
|
+
'released': False,
|
|
278
|
+
},
|
|
279
|
+
)
|
|
280
|
+
top = next((r for r in res.added if idx.views[r].heading == heading.strip()), None)
|
|
281
|
+
return {
|
|
282
|
+
'ok': True,
|
|
283
|
+
'refs': res.added,
|
|
284
|
+
'lines': [f'Imported {rel} → {top or target} ({len(res.added)} section(s)); delete {rel} when ready.'],
|
|
285
|
+
}
|
diffpilot/ops.pyi
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
from diffpilot import events as events, prompts as prompts, store as store
|
|
3
|
+
from diffpilot.config import Config as Config, DPError as DPError
|
|
4
|
+
from diffpilot.events import git_head as git_head
|
|
5
|
+
from diffpilot.index import Index as Index, Locked as Locked, now as now
|
|
6
|
+
from diffpilot.schemas import EditOp as EditOp
|
|
7
|
+
from diffpilot.store import clip as clip
|
|
8
|
+
|
|
9
|
+
def open_index(cfg: Config) -> Index: ...
|
|
10
|
+
def sync_manual(cfg: Config, idx: Index) -> None: ...
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class Applied:
|
|
14
|
+
lines: list[str] = field(default_factory=list)
|
|
15
|
+
ops: list[dict] = field(default_factory=list)
|
|
16
|
+
warnings: list[str] = field(default_factory=list)
|
|
17
|
+
refs: list[str] = field(default_factory=list)
|
|
18
|
+
event_id: str | None = ...
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Plan:
|
|
22
|
+
texts: dict[str, str]
|
|
23
|
+
orig: dict[str, str]
|
|
24
|
+
ops: list[dict] = field(default_factory=list)
|
|
25
|
+
warnings: list[str] = field(default_factory=list)
|
|
26
|
+
links: list[tuple[str, str]] = field(default_factory=list)
|
|
27
|
+
|
|
28
|
+
def plan_ops(cfg: Config, idx: Index, ops: list[EditOp], shown: dict[str, str], allowed: tuple[str, ...], owner_only: bool = False, strict: bool = True) -> Plan: ...
|
|
29
|
+
def preview(cfg: Config, plan: Plan, budget_chars: int) -> str: ...
|
|
30
|
+
def apply_ops(cfg: Config, idx: Index, ops: list[EditOp], shown: dict[str, str], origin: str, allowed: tuple[str, ...], event: dict, owner_only: bool = False, files: list[str] | None = None) -> Applied: ...
|
|
31
|
+
def import_doc(cfg: Config, rel: str, target: str) -> dict: ...
|