Skip to content

fix(cli): remap temporal subcommands onto the v0.7.0 engine APIs - #1987

Merged
pkupt merged 3 commits into
semantica-agi:mainfrom
charan-rathore:fix-temporal-cli-remap-1809
Oct 11, 2026
Merged

pkupt merged 3 commits into
semantica-agi:mainfrom
charan-rathore:fix-temporal-cli-remap-1809

Conversation

@charan-rathore

Copy link
Copy Markdown
Contributor

Description

All five semantica temporal subcommands crash on v0.7.0 because the CLI wrappers call methods and constructors that no longer exist on the engine classes. This re-maps each subcommand onto the APIs that actually exist, following the approach outlined in the issue thread.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)

Related Issues

Fixes #1809

Changes Made

  • snapshot -> TemporalGraphQuery.reconstruct_at_time() over the persisted memory-backend graph (_load_context_graph(...).to_kg_dict())
  • query -> TemporalGraphQuery.query_at_time(), with a new optional --at flag (defaults to the current time); the help text notes the query string is reserved for future query parsing, matching the engine
  • history -> TemporalReasoningEngine.timeline_of() over the graph's facts, with the --since filter applied to event timestamps
  • distance -> implemented as the absolute delta between the two timestamps via normalize_timestamp(); JSON output carries distance_seconds/distance_days. The --history flag is dropped since no behavior exists behind it
  • allen -> each start/end spec parsed with normalize_interval() and compared with TemporalReasoningEngine().relation() (the old config= kwarg is what raised TemporalReasoningEngine() takes no arguments)
  • Engine-side: reconstruct_at_time() and timeline_of() still read the legacy source/target keys while ContextGraph.to_kg_dict() (the documented adapter for these consumers) emits source_id/target_id, silently dropping every relationship; both now accept either key, matching the fallback already used elsewhere in temporal_query
  • New tests/cli/test_cli_temporal.py: a CliRunner smoke test per subcommand against a small fixture graph (13 tests)

Testing

  • Tested locally
  • Added tests for new functionality
  • Package builds successfully (python -m build)

Test Commands

# RED on main: all five crash exactly as the issue reports
semantica temporal history entity_alice      # AttributeError: 'TemporalVersionManager' object has no attribute 'history'
semantica temporal query status              # 'TemporalGraphQuery' object has no attribute 'query'
semantica temporal snapshot --at ...         # ... has no attribute 'snapshot'
semantica temporal distance --event1 a ...   # ... has no attribute 'distance'
semantica temporal allen --interval1 ...     # TypeError: TemporalReasoningEngine() takes no arguments

# GREEN with this change: all five succeed (verified against a fixture graph)
pytest tests/cli/test_cli_temporal.py        # 13 passed
pytest tests/cli/ tests/test_cli_commands.py tests/test_cli_foundation.py   # 434 passed, 1 skipped, 3 xfailed
pytest tests/test_395_temporal_semantics_comprehensive.py tests/test_401_temporal_provenance_export.py tests/kg/test_temporal_query_rewriter.py tests/kg/test_temporal_reasoning.py tests/change_management/test_temporal_versioning.py   # 233 passed
python -m build                              # semantica-0.7.0-py3-none-any.whl

Documentation

  • No documentation changes needed (subcommand help text updated in place)

Breaking Changes

Breaking Changes: No

(temporal distance loses its --history flag, but the subcommand has never executed successfully on any v0.7.0 install, so no working invocation breaks.)

Checklist

  • My code follows the project's style guidelines (new code is black==26.5.1-clean; unrelated pre-existing formatting in the touched files is left alone)

All five 'semantica temporal' subcommands crashed on v0.7.0 because the
CLI wrappers called methods and constructors that no longer exist on the
engine classes (issue #1809):

- snapshot -> TemporalGraphQuery.reconstruct_at_time() on the persisted
  memory-backend graph (loaded via _load_context_graph().to_kg_dict()).
- query -> TemporalGraphQuery.query_at_time(); new optional --at flag
  (defaults to now). Help text notes the query string is reserved for
  future query parsing, matching the engine.
- history -> TemporalReasoningEngine.timeline_of() over the graph's
  facts, with the --since filter applied to event timestamps.
- distance -> implemented as the absolute delta between the two
  timestamps via normalize_timestamp(); JSON output carries
  distance_seconds/distance_days. The --history flag is dropped since
  no behavior exists behind it.
- allen -> parse each start/end spec with normalize_interval() and call
  TemporalReasoningEngine().relation() (no config kwarg, which is what
  raised 'TemporalReasoningEngine() takes no arguments').

Two engine-side spots still assumed the legacy source/target keys while
ContextGraph.to_kg_dict() (the documented adapter for these consumers)
emits source_id/target_id, which silently dropped every relationship
from reconstruct_at_time() and timeline_of(); both now accept either
key, matching the fallback already used elsewhere in temporal_query.

Each subcommand gets a CliRunner smoke test against a small fixture
graph (13 tests). Verified: 5/5 subcommands crash on main and succeed
with this change; the CLI suites (434 passed) and the temporal suites
(233 passed) stay green.

Signed-off-by: Charan Rathore <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 10, 2026 15:06
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@qodo-code-review

Copy link
Copy Markdown

ⓘ Qodo reviews are paused because the subscription is no longer active. Ask your workspace admin to reactivate the subscription to resume reviews. Manage billing

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Restore temporal CLI commands using v0.7.0 engine APIs

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Remap all five temporal commands to supported engine APIs so they run on v0.7.0.
• Preserve relationships from persisted graphs in temporal snapshots and entity histories.
• Add CLI smoke tests for temporal results, filters, and invalid input.
Diagram

graph TD
  CLI["Temporal CLI"] --> Store[("Persisted graph")] --> Adapter["KG adapter"] --> Query["Temporal query"] --> Output["CLI output"]
  Adapter --> Reasoning["Temporal reasoning"] --> Output
  CLI --> Reasoning
Loading
High-Level Assessment

Use the existing ContextGraph adapter and supported engine APIs, as this PR does. Reintroducing the removed engine methods solely for the CLI would expand the API surface without addressing the relationship-key mismatch.

Files changed (4) +363 / -46

Bug fix (3) +145 / -46
cli.pyReconnect all five temporal commands to supported APIs +136/-43

Reconnect all five temporal commands to supported APIs

• Snapshot, query, and history now use the persisted graph and current temporal engines; query gains an optional --at time. Distance calculates an absolute timestamp delta, Allen compares normalized intervals, and the nonfunctional distance --history flag is removed.

semantica/cli.py

temporal_query.pyRetain relationships in reconstructed KG snapshots +6/-2

Retain relationships in reconstructed KG snapshots

• Reconstruction accepts both legacy source/target endpoints and the source_id/target_id fields emitted by ContextGraph.to_kg_dict(). This prevents otherwise-valid relationships from disappearing from snapshots and point-in-time queries.

semantica/kg/temporal_query.py

temporal_reasoning.pyInclude adapted relationships in entity timelines +3/-1

Include adapted relationships in entity timelines

• Timeline matching accepts either relationship endpoint naming scheme, allowing histories to include events from graphs exported through the ContextGraph adapter.

semantica/kg/temporal_reasoning.py

Tests (1) +218 / -0
test_cli_temporal.pyExercise temporal commands through CliRunner +218/-0

Exercise temporal commands through CliRunner

• Adds 13 smoke tests covering all five commands against a small graph fixture. Cases check relationship validity, query timing, history filtering, absolute distance, Allen relations, and malformed input.

tests/cli/test_cli_temporal.py

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Temporal commands read the wrong graph ✓ Resolved
Description
_load_temporal_kg() always reads the memory-backend JSON file instead of resolving the configured
graph backend. With a non-memory backend selected, snapshot, query, and history return empty or
stale memory-file data rather than data from that backend.
Code

semantica/cli.py[3687]

+    return _load_context_graph(cli_ctx).to_kg_dict()
Evidence
The new helper is shared by all three graph-reading temporal commands. Its loader constructs a
ContextGraph from the memory JSON path, whereas other CLI paths resolve backend selection and
construct a GraphStore.

semantica/cli.py[3684-3687]
semantica/cli.py[3729-3731]
semantica/cli.py[3768-3772]
semantica/cli.py[3812-3813]
semantica/cli.py[1294-1320]
semantica/cli.py[1462-1481]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Temporal graph commands silently read the memory file even when another graph backend is selected.
## Fix Focus Areas
- semantica/cli.py[3684-3687]
- semantica/cli.py[3729-3731]
- semantica/cli.py[3768-3772]
- semantica/cli.py[3812-3813]
## Recommended Fix
Resolve the selected backend before loading the graph. Read and adapt the selected store into the temporal engine's entity/relationship shape; if that backend cannot be read, return an explicit unsupported-backend error instead of memory-file results.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Recorded decisions have no history ✓ Resolved
Description
temporal_history() passes exported graph facts to timeline_of(), but the export nests a
decision's recorded_at under metadata while the timeline reads only top-level temporal fields. A
normally recorded decision without explicit validity dates therefore produces no event for itself,
despite having a recording timestamp.
Code

semantica/cli.py[R3812-3813]

+        graph = _load_temporal_kg(cli_ctx)
+        events = TemporalReasoningEngine().timeline_of(entity_id, graph)
Evidence
Decision creation supplies recorded_at to add_node, which retains it as metadata. The KG adapter
exports that metadata nested, while _events_for_fact() checks top-level recorded_at and validity
bounds only.

semantica/context/context_graph.py[4503-4541]
semantica/context/context_graph.py[5050-5061]
semantica/context/context_graph.py[1139-1170]
semantica/context/context_graph.py[3648-3697]
semantica/kg/temporal_reasoning.py[165-180]
semantica/kg/temporal_reasoning.py[234-255]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
History omits ordinary recorded decisions because their recording timestamps are nested in exported metadata.
## Fix Focus Areas
- semantica/cli.py[3812-3813]
- semantica/context/context_graph.py[3648-3697]
- semantica/kg/temporal_reasoning.py[234-255]
## Recommended Fix
Ensure the facts passed to `timeline_of()` expose `recorded_at` at the level its event extraction reads, while preserving the graph's metadata. Add a CLI test using a persisted decision without explicit validity dates.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

3. Adjacent intervals appear to overlap ✓ Resolved
Description
_parse_allen_interval() uses normalize_interval(..., "second"), which expands each interval's
end to the last microsecond of its ending second. When one supplied end equals the next supplied
start, relation() consequently returns overlaps instead of meets.
Code

semantica/cli.py[3697]

+    return engine.normalize_interval(parts[0].strip(), parts[1].strip(), "second")
Evidence
The normalization method expands finite ends, while the relation method requires exact endpoint
equality for meets. For 2025-01-01T00:00:00Z/2025-01-02T00:00:00Z followed by an interval
starting 2025-01-02T00:00:00Z, the expanded first end is later than the second start.

semantica/cli.py[3690-3697]
semantica/kg/temporal_reasoning.py[43-69]
semantica/kg/temporal_reasoning.py[213-230]
semantica/kg/temporal_reasoning.py[323-330]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Expanding CLI interval ends changes Allen relations for adjacent intervals.
## Fix Focus Areas
- semantica/cli.py[3690-3697]
- semantica/kg/temporal_reasoning.py[43-69]
- semantica/kg/temporal_reasoning.py[213-230]
## Recommended Fix
Parse the supplied start and end as exact temporal values and construct a validated TemporalInterval without end-of-second expansion. Test intervals whose shared endpoint should yield `meets`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Subsecond distances become zero ✓ Resolved
Description
temporal_distance() normalizes both input timestamps to whole seconds before subtracting them.
Distinct valid ISO timestamps within the same second therefore produce distance_seconds: 0 and
lose their original fractional precision in the returned timestamps.
Code

semantica/cli.py[R3855-3857]

+        t1 = engine.normalize_timestamp(event1, "second")
+        t2 = engine.normalize_timestamp(event2, "second")
+        seconds = abs((t2 - t1).total_seconds())
Evidence
normalize_timestamp at second granularity replaces microseconds with zero. The new distance
calculation uses those rounded values for both subtraction and output, so inputs such as
00:00:00.100Z and 00:00:00.900Z produce zero instead of 0.8 seconds.

semantica/cli.py[3854-3863]
semantica/kg/temporal_reasoning.py[199-212]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Distance calculation discards fractional seconds before computing the delta.
## Fix Focus Areas
- semantica/cli.py[3854-3863]
- semantica/kg/temporal_reasoning.py[199-212]
## Recommended Fix
Parse both timestamps without rounding, then subtract the parsed values and serialize those same values. Add a test with two timestamps in the same second.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can tweak Display settings with a live preview to see your comment before it ships

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread semantica/cli.py Resolved
Comment thread semantica/cli.py Resolved
Comment thread semantica/cli.py Resolved
Comment thread semantica/cli.py Resolved
Review follow-ups on the temporal remap, each reproduced before fixing:

- temporal allen parsed intervals through normalize_interval(..., "second"),
  which expands the end to the last microsecond of its second, so adjacent
  intervals reported overlaps instead of meets. Parse exact values and build
  the TemporalInterval directly.
- temporal distance normalized both timestamps to whole seconds first, so
  distinct subsecond timestamps collapsed to distance_seconds 0. Parse exact
  values and subtract.
- temporal history missed facts recorded without explicit validity dates:
  the export keeps recorded_at under properties/metadata while the engine
  reads it at the fact's top level. Lift it (normalized to UTC) when loading.
- temporal snapshot/query/history read the memory-backend file regardless of
  the configured backend; with --store neo4j they returned empty memory-file
  data with exit 0. Raise an explicit not-wired error instead, matching the
  CLI's existing guard wording.

Signed-off-by: Charan Rathore <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 10, 2026 15:17

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@charan-rathore

Copy link
Copy Markdown
Contributor Author

Addressing all four Qodo findings. I reproduced each one first, then fixed it; 7bbc154 contains the fixes and regression tests.

1. Temporal commands read the wrong graph (High) — confirmed, fixed. With --store neo4j, temporal snapshot exited 0 and returned the empty memory-file graph instead of touching the configured backend. _load_temporal_kg() now checks the resolved backend and raises an explicit "not wired for the 'neo4j' backend yet" error for non-memory backends, matching the CLI's existing guard wording.

2. Recorded decisions have no history (High) — confirmed, fixed. Recorded a decision without --valid-from/--valid-until: temporal history returned 0 events because the export keeps recorded_at under properties/metadata while timeline_of() reads it at the fact's top level. _load_temporal_kg() now lifts recorded_at to the top level (normalized to UTC) when the fact has none, so a recorded decision produces its history event. Verified end to end: record then history now returns the recording event.

3. Adjacent intervals appear to overlap (Medium) — confirmed, fixed. temporal allen with ...T01:00:00Z as one interval's end and the next's start returned overlaps; correct is meets. Cause was exactly as diagnosed: normalize_interval(..., "second") expands the end to the last microsecond of its second. _parse_allen_interval() now parses exact values and constructs the TemporalInterval directly — adjacent intervals report meets, and end-before-start is rejected.

4. Subsecond distances become zero (Medium) — confirmed, fixed. temporal distance between ...00.500 and ...00.900 returned distance_seconds: 0 after whole-second normalization. It now parses both timestamps exactly and subtracts them — the same inputs return 0.4, and the returned timestamps keep their original precision.

Regression tests added for all four (adjacent-meets, subsecond distance, recording event in history, non-memory backend rejection). Full run: 18/18 temporal CLI tests, 27/27 tests/cli, 529 temporal-related tests green.

@pkupt pkupt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified the remap on the branch. It targets the APIs that actually exist on v0.7.0 (the TemporalGraphQuery / TemporalReasoningEngine signatures all match), and the two engine-side changes are load-bearing rather than cosmetic: ContextGraph.to_kg_dict() emits source_id/target_id (semantica/context/context_graph.py:3684), so without the fallback in reconstruct_at_time/timeline_of the entity lookup resolves to the string "None" and every relationship is silently dropped. The recorded_at lift is needed for the same reason, since add_node/add_edge keep extra fields in metadata/properties, which to_kg_dict() nests.

Two things to fix before merge.

  1. semantica/cli.py:3971 — the two blank lines between temporal_allen and @main.group(invoke_without_command=True) were dropped, so there are now zero. Every other @main.group in the file has two, and pre-commit runs black 24.1.1 plus flake8 7.0.0 with only E203,W503 ignored, so E305 fires and pre-commit run --all-files is red here. CI does not run pre-commit, which is why the checks stay green.

  2. temporal history --format json emits non-ISO timestamps ("2025-03-01 12:00:00+00:00", space-separated, from _jecho's default=str), while temporal distance --json in the same group emits 2025-01-01T00:00:00+00:00. tests/cli/test_cli_temporal.py:295 pins the space form with startswith("2025-03-01 12:00:00"), so the inconsistency becomes the contract. Please serialize through serialize_temporal_value/relationship_to_json_ready, or at least drop that format assertion.

Minor, non-blocking.

  • parse_temporal_value raises TemporalValidationError on bad input; it never returns None (semantica/kg/temporal_model.py:83-109). So the None guards at cli.py:3735, 3740 and 3910 are unreachable and their messages never appear; invalid input still exits non-zero through the generic Semantica error card. For the same reason the naive-timezone guards (cli.py:3743-3746, and the _aware helper in temporal_history) are dead, since parse_temporal_value always returns an aware UTC datetime.

  • temporal history now serves a timeline_of event stream instead of version records, leaving TemporalVersionManager.list_versions() (suggested in the issue) unreachable from the CLI. Fine as a scope call, but worth confirming the intended semantics.

  • Non-memory backends are gated with an explicit error rather than adapted. Reasonable for now, worth noting as a known limitation.

…ze temporal history JSON

- Restore the two blank lines after temporal_allen's error-handling return
  so the provenance @main.group no longer trips flake8 E302/E305 (the
  pre-commit hook runs flake8 with --max-line-length=88
  --extend-ignore=E203,W503).
- Route temporal history --format json through
  temporal_structure_to_json_ready, which serializes every datetime via
  serialize_temporal_value, so timestamps come out ISO 8601 with Z, same
  as temporal distance --json. Repin the CLI test to the ISO form.

Signed-off-by: Charan Rathore <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 11, 2026 05:37

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@charan-rathore

Copy link
Copy Markdown
Contributor Author

Thanks for the close read, @pkupt. Both items are fixed in 7220688:

1. Blank lines / E305. Restored the two blank lines before the provenance group decorator after temporal_allen's error-handling return. I checked locally with the exact pre-commit flake8 args (--max-line-length=88 --extend-ignore=E203,W503): the E302/E305 at that spot is gone, and the diff adds no new violations (the file has pre-existing E501s elsewhere that just shifted line numbers).

2. JSON timestamps. temporal history --format json now serializes through temporal_structure_to_json_ready, which routes every datetime through serialize_temporal_value, so timestamps come out ISO 8601 with Z, consistent with temporal distance --json. The test that pinned the space-separated form now pins the ISO form.

On the minor notes:

  • You're right that the None and naive-timezone guards in these paths are unreachable: parse_temporal_value either raises or returns aware UTC. I left them in place to keep this diff focused on the review items; happy to strip the dead guards in a follow-up if you'd like.
  • History output: the timeline_of event stream ({timestamp, change_type, fact}) is the intended shape for this fix, since the issue was about the history command crashing and the distance math being off. Switching history to version records would be a separate behavior change; glad to open a follow-up issue if you want that output here.
  • Non-memory backend: agreed, that's the current limitation. The guard now fails loudly instead of producing wrong output.

Tests run locally: tests/cli (27 passed), kg temporal tests (99 passed), temporal semantics/provenance suites (141 passed).

@pkupt pkupt left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-checked 7220688. Both items are addressed: the provenance group has its two blank lines back, and temporal history --format json now serializes through temporal_structure_to_json_ready, so timestamps come out as ISO 8601 (2025-01-01T00:00:00Z), consistent with temporal distance --json; the test assertion was updated to match. I re-ran the new test file (18 passed) and all five subcommands on the branch (exit 0), and the merge against main is clean. One optional follow-up, not blocking: the non-JSON output of temporal history (its default --format table) still renders timestamps through _pprint's default=str, so that path shows the space-separated form while the JSON path is now ISO.

@pkupt
pkupt merged commit 14c1daf into semantica-agi:main Oct 11, 2026
12 checks passed
charan-rathore added a commit to charan-rathore/charan-rathore that referenced this pull request Oct 11, 2026
@charan-rathore
charan-rathore deleted the fix-temporal-cli-remap-1809 branch October 11, 2026 06:28
OntologyAgent pushed a commit to OntologyAgent/semantica-cn that referenced this pull request Oct 11, 2026
…a-agi#1970 semantica-agi#1987 semantica-agi#1990)

非回环 --host 的来源放行、IPv6 方括号写法、--port 0 行为、
create_app() 统一默认来源、SEMANTICA_CORS_ORIGINS 默认值扩充。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] semantica temporal CLI: all five subcommands crash (AttributeError/TypeError) — CLI wrappers drifted from the temporal engines

3 participants